aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why no static members 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 "Why no static members in inner classes?" Watch "Why no static members in inner classes?" New topic
Author

Why no static members in inner classes?

Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Why can't you have any static members inside inner classes? I understand that you can't have static members inside local classes (which are out of scope everywhere except the block in which they are defined) and anonymous classes (they have no name, so how would you get to a class variable), but I don't quite understand why static variables are not allowed inside an inner class.
An inner class has a definite name, the being "<enclosing class name>.<inner class name>" and it (assuming it is public), can be accessed by other classes. Therefore, I don't understand why static members are not allowed within an inner class.
Take a look at this example (which should fail to compile):

This is basically a contrived example that is an attempt to make an Iterator for a new list class that can count the number of instances of it that are currently alive.
Why isn't this allowed?
Thanks,
Corey


SCJP Tipline, etc.
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
I think basically that the inner class has no independant existance apart from the scope of an instance of the enclosing class, so there is no concept of being able to have some data that "persists" whether or not an instance exists.
Top level classes can have static members because the class is always just "one step" away from actual instantiation via the new keyword. But for an inner class, First you must have an instance of the enclosing class THEN you can instantiate the inner class.
I suppose they could have defined this behavior differently, and allowed statics in inner classes, but the fact is they are currently illegal. Maybe it was a design trade-off for simplifying compilation. At any rate, it's better to think of it in terms of what I wrote above, and just remember they are illegal.


Rob
SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why no static members in inner classes?