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

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

Barbara Streisand
Release: 2024-12-14 11:17:11
Original
697 people have browsed it

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

Referencing the Outer Class from the Inner Class

In the provided code snippet, you have nested classes OuterClass and InnerClass. You aim to access the parent class (OuterClass) from an instance of the inner class (InnerClass) without modifying the inner class's code.

Using OuterClass.this

Within the InnerClass, you can use the expression OuterClass.this to refer to the enclosing instance of OuterClass. This expression qualifies the this keyword to indicate the enclosing instance. Here's a modified version of your code:

public class OuterClass {

    public class InnerClass {
        private String name = "Peakit";
        
        public OuterClass outer() {
            return OuterClass.this;
        }
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        InnerClass inner = outer.new InnerClass();
        
        OuterClass anotherOuter = inner.outer();

        if(anotherOuter == outer) {
             System.out.println("Was able to reach out to the outer object via inner !!");
        } else {
             System.out.println("No luck :-( ");
        }
    }
}
Copy after login

When you run this code, the outer() method in InnerClass returns the enclosing instance of OuterClass, which you can then compare with the original OuterClass instance.

Package-Level Access (Not Recommended)

Through experimentation, it has been found that the field holding the reference to the outer class has package-level access. This means you can technically access the outer class through reflection:

Field field = InnerClass.class.getDeclaredField("this");
field.setAccessible(true);
OuterClass outer = (OuterClass) field.get(inner);
Copy after login

Note: This approach is discouraged by the Java Language Specification and may not be reliable across different Java versions.

The above is the detailed content of How Can I Access the Outer Class 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template