Accessing Outer Class Instance from Anonymous Inner Class
In Java, an anonymous inner class is a nested class without an explicit name. It is typically used to implement event handlers or to override abstract methods in an outer class.
Suppose you have an outer class named a with a method called doStuff that takes an InnerClass parameter. Within the outer class, you create an anonymous inner class as a parameter to doStuff.
From within the anonymous inner class, you want to access a method in the outer class, such as otherMethod. How can you refer to the outer class instance from the anonymous inner class?
The answer lies in using the OuterClass.this syntax. This expression allows you to access the enclosing instance of the outer class. In your example, to call otherMethod from the anonymous inner class, you would use:
a.this.otherMethod();
This syntax ensures that you are referencing the correct instance of the outer class, even if there are multiple instances of the class in scope.
The above is the detailed content of How to Access an Outer Class Instance from an Anonymous Inner Class in Java?. For more information, please follow other related articles on the PHP Chinese website!