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.
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.