|

The keyword this always refers to the currently (executing) object,
hence when you use it inside the inner class’s instance methods, it refers to currently-executing
instance of that inner class. Now, if you want to refer to the enclosing
instance (of outer class), how will you do it? Generally, the outer instance is
implicitly available to the inner class. However, if you wish to (say
for code clarity sake) explicitly refer the outer instance, you can do so by
calling it OuterClassName.this. Listing 4.3 demonstrates how to refer
enclosing instance as well as the inner class instance .
The keyword this within InnerOne refers to the instance of InnerOne. If you wish to explicitly access the OuterOne’s instance, you need to say OuterOne.this. However you hardly need to explicitly access the enclosing class instance as it is implicitly available within the member inner class. For example, earlier we saw in listing 4.2 that you can directly access the variable outerVar of OuterOne from InnerOne. You need not say OuterOne.this.outerVar, though it is also correct.
Listing 4.3 demonstrates the difference between the instances of OuterOne and InnerOne. The selfReferenceTest() method would print the textual representation of two objects. You can test the code in listing 4.3 with a Tester class as:
package com.example.scjp.studykit;
public class Tester {
public static void main(String[] args) {
OuterOne outer = new OuterOne();
OuterOne.InnerOne inner = outer.new InnerOne();
inner.selfReferenceTest();
System.out.println("Enclosing instance: " + outer);
}
}
The output will be something like:
Inner class instance: OuterOne$InnerOne@3f5d07
Enclosing instance: OuterOne@f4a24a
Enclosing instance: OuterOne@f4a24a
As you can see from the output, the reference outer and OuterOne.this from within the InnerOne are same. It is so because they are referring to the same object.