"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access an Outer Class Instance from an Anonymous Inner Class in Java?

How to Access an Outer Class Instance from an Anonymous Inner Class in Java?

Published on 2024-11-10
Browse:701

How to Access an Outer Class Instance from an Anonymous Inner Class in Java?

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3