Home > Java > javaTutorial > body text

How can you access methods from the outer class within an anonymous inner class?

Susan Sarandon
Release: 2024-11-11 16:43:02
Original
231 people have browsed it

How can you access methods from the outer class within an anonymous inner class?

Accessing the Outer Class from an Anonymous Inner Class

In the code snippet provided:

public class a {
    public void otherMethod(){}
    public void doStuff(String str, InnerClass b){}
    public void method(a){
        doStuff("asd",
            new InnerClass(){
                public void innerMethod(){
                    otherMethod();
                }
            }
        );
    }
}
Copy after login

The question arises: can we directly access the outer class methods from the anonymous inner class?

Solution: Using OuterClassName.this

To refer to the outer class from within an anonymous inner class, use the syntax OuterClassName.this. In this example, to call the otherMethod() method of the outer class a, you would use a.this.otherMethod().

Therefore, the complete version of the innerMethod() method would be:

public void innerMethod(){
    a.this.otherMethod();
}
Copy after login

The above is the detailed content of How can you access methods from the outer class within 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