Home >Java >javaTutorial >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!