Java Reference
In-Depth Information
13. System.out.println(B.this.x);
14. System.out.println(A.this.x);
15. }
16. }
17. }
18.
19. public static void main(String [] args) {
20. A a = new A();
21. A.B b =a.new B();
22. A.B.C c = b.new C();
23. c.go();
24. }
25.}
Nested Inner Classes
Notice in the A class it has a nested class B that also has a nested class C. This is
perfectly valid but probably not something you will ever see in the real world.
A breakdown of the code in the A class follows:
1. An object of type C is instantiated using an instance of A and B , and its go method is
invoked.
2. The x on line 11 is implicitly referring to this.x , so 11 and 12 display the same value,
which is 20 . (The this reference inside the C class refers to the C object.)
3. To access the x field of the B object, prefix the this keyword with the B class name:
B.this.x . Line 13 displays 15 .
4. Similarly, the x in A is A.this.x , which is displayed on line 14.
Keep in mind the syntax A.this and B.this is unique to inner classes only. The output
of running main is
20
20
15
10
Search WWH ::




Custom Search