Retrieving the Outer Class Instance from an Inner Class
Consider the following code, where the goal is to access the outer class object from an inner class instance:
public class OuterClass { public class InnerClass { private String name = "Peakit"; } public static void main(String[] args) { OuterClass outer = new OuterClass(); InnerClass inner = outer.new InnerClass(); // Retrieve the outer class instance... OuterClass anotherOuter = ?? ; } }
Accessing the Outer Class Instance from Within the Inner Class
Within the inner class, you can utilize the OuterClass.this expression to refer to the enclosing instance. This technique, known as "Qualified This," allows you to access members of the outer class from within the inner class.
public OuterClass getOuter() { return OuterClass.this; }
Accessing the Outer Class Instance Without Modifying the Inner Class
If you don't have the ability to modify the inner class, it may be possible to access the outer class instance through package-level access to the enclosing instance field, denoted by this$0.
OuterClass outerRef = inner.this;
Additional Notes
The above is the detailed content of How Can I Access the Outer Class Instance from an Inner Class in Java?. For more information, please follow other related articles on the PHP Chinese website!