Java Reference
In-Depth Information
3. The repeat field of x is set to 2 on line 15.
4. Line 16 invokes the Inner object's go method, which prints out the greeting field of y
twice.
Therefore, the output is
Hello, Outer
Hello, Outer
Inner Classes Behind the Scenes
Something interesting to know about inner classes is that a JVM does not have a concept
of inner classes. They are a compile-time feature, and the compiler actually writes a top-
level class for every inner class that you declare. This new top-level class needs some
special fi elds and methods so that it can access all the members of its enclosing class.
For example, the inner class contains an implicit reference to its outer class object.
When the Outer class example from this section is compiled, two bytecode fi les are
created: Outer.class and Outer$Inner.class . (Inner classes are one of the only
times you will ever see a dollar sign in an identifi er.) The compiler wrote a class named
Outer$Inner to represent our inner class. You cannot instantiate an Outer$Inner object
explicitly. You have to use the appropriate inner class syntax.
Inner classes also have a special syntax for accessing a fi eld in the outer class that you
need to use if the outer class shares a name with a fi eld or method from the inner class. The
following contrived example demonstrates this syntax. Study the code carefully and see if
you can determine the output:
1. public class A {
2. private int x = 10;
3.
4. public class B {
5. private int x = 15;
6.
7. public class C {
8. private int x = 20;
9.
10. public void go() {
11. System.out.println(x);
12. System.out.println(this.x);
Search WWH ::




Custom Search