Home > Java > javaTutorial > How Can I Access the Outer Class Instance from an Inner Class in Java?

How Can I Access the Outer Class Instance from an Inner Class in Java?

DDD
Release: 2025-01-02 16:55:41
Original
677 people have browsed it

How Can I Access the Outer Class Instance from an Inner Class in Java?

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 = ?? ;
    }
}
Copy after login

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;
}
Copy after login

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;
Copy after login

Additional Notes

  • The name this$0 is recognized by Java, although its use is discouraged in the Java Language Specification.
  • It's generally considered good practice to avoid relying on package-level access for accessing the enclosing instance.
  • Adding a method to the inner class to explicitly return the outer class instance is a more robust solution if you have control over its modification.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template