Home  >  Article  >  Java  >  How to Access Methods of the Outer Class from an Anonymous Inner Class?

How to Access Methods of the Outer Class from an Anonymous Inner Class?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 01:45:02380browse

How to Access Methods of the Outer Class from an Anonymous Inner Class?

Accessing the Outer Class from an Anonymous Inner Class

Within an anonymous inner class, accessing members of the enclosing outer class can be achieved using a specific syntax.

Consider the following code snippet:

public class Outer {
    public void otherMethod() {}
    public void doStuff(String str, InnerClass b) {}
    public void method(Outer a) {
        doStuff("asd", new InnerClass() {
            public void innerMethod() {
                // How to access outer.otherMethod() here?
            }
        });
    }
}

To access the outerMethod() method of the outer class from the anonymous inner class, Java provides the OuterClassName.this syntax. In this case, you would use:

Outer.this.otherMethod();

This allows the anonymous inner class to access the outer class's members as if they were defined within the inner class itself. So, the code within innerMethod() can now access outerMethod() using the syntax:

Other.this.otherMethod();

The above is the detailed content of How to Access Methods of the Outer Class from an Anonymous Inner Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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