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 we declare static members (variable/instance variables) inside an inner class or a method local inner class?
For inner class, is it because we need to have an instance of that class instantiated before we can use the static member ? But according to the syntax, to use a static member, we don't need to instantiate any instance . That is a contradiction.
For method local inner class, is it because the inner class instance will be eligible for garbage collection when the method exits.If we have a static member declared, we cannot use it outside the scope of the method.
Outer.Inner.myStatic? This won't work, because Inner is non-static and thus needs to be accessed through an instance of Outer. So would you do:
myOuter.Inner.myStatic? That seems silly. The point of a static variable is that it's in global space. You don't want to access them through instances.
Since the fields are static anyway, you might as well just declare them in the enclosing class directly.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Joined: Nov 01, 2011
Hi, I guess inner class can be private/protected. Even though we declare a public static variable inside it, this variable cannot be accessed by other classes outside the outer class .
The child class in a different package from its parent class can inherit this inner class, but cannot access this static variable by creating reference Outer.Inner i = new Outer().new Inner() ; And there is a point that child class from a different package can only access its parent's protected variables thru inheritance, not through reference.
Therefore, declaring a static member for inner class does no help.
gurpeet singh wrote:but if we declare the static variable as final then we are able to define it in the inner class. any explanation for that ?
Well, this is not true -- so, no need to explain..... However, I will speculate that you probably saw an example of a compile time constant (that is declared as a static variable). Compile time constants are allowed, even if the constant variable is a static variable.