Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-11-11 19:07:03
Original
381 people have browsed it

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

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

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

a.this.otherMethod();
Copy after login

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!

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