Java Reference
In-Depth Information
Let's add an instance variable to the outer class and access that instance variable inside the inner class. To keep
the example simple, you have added a new getValue() method to the Inner class in order to access the Outer class's
instance variable called dummy . The modified code is as follows:
public class Outer {
int dummy = 101;
public class Inner {
public int getValue() {
// Access Outer's class dummy field
int x = dummy + 200;
return x;
}
}
}
The decompiled code for Outer.class and Outer$Inner.class files are as follows:
// Decompiled code from Outer.class file
public class Outer {
int dummy = 0;
public Outer() {
dummy = 101;
}
}
// The decompiled code from Outer$Inner.class file
public class Outer$Inner {
final Outer this$0;
public Outer$Inner(Outer outer) {
this$0 = outer;
super();
}
public int getValue() {
int x = this$0.dummy + 200;
return x;
}
}
Note the use of this$0.dummy to access the instance variable of the Outer class inside the getValue() method
of the Inner class. The dummy instance variable in the Outer class has a package-level access. Since an inner class is
always the part of the same package as its enclosing class, this method of referring to the instance variable of the Outer
class from outside works fine. However, if the instance variable dummy is declared private , the Outer$Inner class code
cannot refer to it directly as it did in the previous example. The compiler uses a different way to access the private
instance variable of the outer class from an inner class. The following is the modified code and the corresponding
decompiled code for the Outer and Inner classes:
// Modified Outer class code with dummy as private instance variable
public class Outer {
private int dummy = 101; // Declare dummy as private
 
Search WWH ::




Custom Search