System.out.println(new Outer().new Inner().i); System.out.println(Inner.i); // line (1) } }
Non static member class cannot have static declarations. But Inner class above extends Outer which has static variable i. And we are able to access i using static reference.How???
Now, let's see the different ways to access a static member:
1. Using the class Jedi:
2. Using an instance of the class Jedi:
3. However, the instance of the class is not at all necessary, since the variable belongs to the class, not to the instance, hence, it could be done using a null reference of the class:
4. From within a method of the class Jedi:
All this simply proves that a variable reference can access the static members of its class or its super classes as long as they are accessible whether the variable reference has been initialized or not.
If we have a set of classes like this:
Notice that the variable name can be accessed through a Child reference, just because the Child extends the Parent class. That does not imply inheritance. Modifying the value of name in the Child class will modify the value in the Parent class. This is the proof that name actually belongs to Parent
Try it, writing a code like this:
You will see that modifying the name field from the Child class will modify the value of the Parent class. This demonstrates that there is such thing as static members inheritance.
When it comes to nested classes, specifically non-static nested classes, they cannot declare new static members, but are allowed to access the static members of the Outer class, or those accessible from its extended classes and implemented interfaces.
It is also important to set clear that non-static nested classes actually are allowed to declare static members, as long as they are final and are initialized to a constant expression. (See JLS 15.28) [ May 27, 2006: Message edited by: Edwin Dalorzo ]
Amirr Rafique
Ranch Hand
Joined: Nov 14, 2005
Posts: 324
posted
0
Thanks Edwin
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.