This is from K & B's book:
Referencing the Inner or Outer Instance from Within the Inner Class:
Within an inner class code, the this reference refers to the instance of the inner class, as you�d probably expect, since this always refers to the currently-executing object. But what if the inner class code wants an explicit reference to the outer class instance the inner instance is tied to? In other words, how do you reference the �outer this�? Although normally the inner class code doesn�t need a reference to the outer class,
since it already has an implicit one it�s using to access the members of the outer class, it would need a reference to the outer class if it needed to pass that reference to some other code as follows:
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Inner class ref is " + this);
System.out.println("Outer class ref is " + MyOuter.this);
}
}
If we run the complete code as follows:
class MyOuter {
private int x = 7;
public void makeInner() {
MyInner in = new MyInner();
in.seeOuter();
}
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Inner class ref is " + this);
System.out.println("Outer class ref is " + MyOuter.this);
}
}
public static void main (
String[] args) {
MyOuter.MyInner inner = new MyOuter().new MyInner();
inner.seeOuter();
}
}
the output is
Outer x is 7
Inner class ref is MyOuter$MyInner@113708
Outer class ref is MyOuter@33f1d7
Inner Classes 9
So the rules for an inner class referencing itself or the outer instance are as follows:
■ To reference the inner class instance itself, from within the inner class code, use this.
■ To reference the �outer this� (the outer class instance) from within the inner class code, use <NameOfOuterClass>.this (example, MyOuter.this).
So, M.Aquino -
Outer class's instance variable can be referenced either directly( Remember nonstatic inner classes have unlimited access to outer class's instance variables.) or through outer class's reference like this . <NameOfTheOuterClass>.this.nameOfTheInstanceVariable.
Hope this helps ...
rgrds,
Jane