Home >Java >javaTutorial >How do I access methods of the outer class from an anonymous inner class?

How do I access methods of the outer class from an anonymous inner class?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 19:07:03455browse

How do I access methods of the outer class from an anonymous inner class?

How to Refer to Outer Class from Anonymous Inner Class

Consider the following snippet, where an anonymous inner class is defined within the method of the a class:

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();
                }
            }
        );
    }
}

Accessing Outer Class Methods

To access the methods of the outer class from the anonymous inner class, you can use the syntax:

OuterClassName.this.<methodName>();

In this example, to call the otherMethod of the a class from the anonymous inner class, you would use:

a.this.otherMethod();

This syntax allows you to access and invoke methods of the outer class from within the anonymous inner class, enabling you to utilize the enclosing instance's functionality effectively.

The above is the detailed content of How do I 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