While going through Oracle docs reading about Nested classes, I found this piece of code whose output I could not understand. Can someone please explain this ?
public class ShadowTest { public int x = 0; class FirstLevel { public int x = 1; void methodInFirstLevel(int x) { System.out.println("x = " + x); System.out.println("this.x = " + this.x); System.out.println("ShadowTest.this.x = " + ShadowTest.this.x); } } public static void main(String... args) { ShadowTest st = new ShadowTest(); ShadowTest.FirstLevel fl = st.new FirstLevel(); fl.methodInFirstLevel(23); } }
The following is the output of this example:
x = 23 this.x = 1 ShadowTest.this.x = 0 //why is 0 printed here? why not 1 because "this" is the object of FirstLevel class.
The original code can be found here
Advertisement
Answer
The local variable x
shadows this.x
and ShadowTest.this.x
.
The instance variable of the inner class (this.x
) shadows the instance variable of the enclosing class (which can be accessed by ShadowTest.this.x
).
System.out.println("x = " + x); // prints the local variable passed to the method System.out.println("this.x = " + this.x); // prints the instance variable of the inner class System.out.println("ShadowTest.this.x = " + ShadowTest.this.x); // prints the instance variable of the enclosing class instance