GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static vars in inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static vars in inner classes" Watch "static vars in inner classes" New topic
Author

static vars in inner classes

Alex Sbityakov
Ranch Hand

Joined: Jul 23, 2001
Posts: 49
Hi all,
Is the following statement true?
Variables defined inside inner classes cannot be static unless the inner class itself is static.
But it is true that non-static inner classes can have static final variables. I've seen the statement above taken to be true in a few mocks. What should I make of it?
Thanks
r balasubramanian
Greenhorn

Joined: Jul 25, 2001
Posts: 11
Yes, it is true. Only top level classes and interfaces can have static members.
R.Balasubramanian
Alex Sbityakov
Ranch Hand

Joined: Jul 23, 2001
Posts: 49
Well then what do you make of the fact the non-static inner classes can have static final member variables? Are they not static?
r balasubramanian
Greenhorn

Joined: Jul 25, 2001
Posts: 11
In continuation to my previous posting please note that static inner class can have static members
R.Balasubramanian
Originally posted by Alex Sbityakov:
Hi all,
Is the following statement true?
Variables defined inside inner classes cannot be static unless the inner class itself is static.
But it is true that non-static inner classes can have static final variables. I've seen the statement above taken to be true in a few mocks. What should I make of it?
Thanks

arie zwijnsma
Greenhorn

Joined: Jul 28, 2001
Posts: 5
i would say the statement is false because a static final member of an inner class is static and because there is no such thing as a 'static inner class', a class with a static modifier is called a nested toplevel class.
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi guys,
When in doubt play with some code
<pre>

public class TestStatic {

// static member class

static class StaticMember {
static int a;
}


// inner class

class Inner {

// the following produces the compiler error
// "inner classes cannot have static declarations"
// static int b;

final static int MAX = 20; // compiles ok - this is a CONSTANT
}
}

</pre>
Hope that helps.

[This message has been edited by Jane Griscti (edited July 28, 2001).]


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
GeeCON Prague 2014
 
subject: static vars in inner classes