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