This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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
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.