Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a reference to the enclosing class from an anonymous inner class in Java? [duplicate]

Tags:

java

oop

I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?

like image 903
Bill the Lizard Avatar asked Aug 27 '08 20:08

Bill the Lizard


People also ask

How do you create an instance of an inner class anonymously in Java?

Object = new Example() { public void display() { System. out. println("Anonymous class overrides the method display()."); } }; Here, an object of the anonymous class is created dynamically when we need to override the display() method.

How do you use an anonymous inner class?

An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class. Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.

How do you refer to outer class from inner class?

If you want your inner class to access outer class instance variables then in the constructor for the inner class, include an argument that is a reference to the outer class instance. The outer class invokes the inner class constructor passing this as that argument.

Can an inner class method have access to the fields of the enclosing class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.


2 Answers

I just found this recently. Use OuterClassName.this.

class Outer {     void foo() {         new Thread() {             public void run() {                 Outer.this.bar();             }         }.start();     }     void bar() {         System.out.println("BAR!");     } } 

Updated If you just want the object itself (instead of invoking members), then Outer.this is the way to go.

like image 195
Frank Krueger Avatar answered Oct 09 '22 07:10

Frank Krueger


Use EnclosingClass.this

like image 43
John Topley Avatar answered Oct 09 '22 09:10

John Topley