Home > Java > javaTutorial > 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
Release: 2024-11-11 01:45:02
Original
446 people have browsed it

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

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

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

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!

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