How can I access the "this" of an outer class from an inner class?

Is it possible to get a reference to this inside a Java inner class?

i.e.

 class Outer { void aMethod() { NewClass newClass = new NewClass() { void bMethod() { // How to I get access to "this" (pointing to outer) from here? } }; } } 
+58
java inner-classes
Apr 28 '10 at 17:22
source share
4 answers

You can access an instance of an outer class as follows:

 Outer.this 
+72
Apr 28 '10 at 17:24
source share

Outer.this

t

 class Outer { void aMethod() { NewClass newClass = new NewClass() { void bMethod() { System.out.println( Outer.this.getClass().getName() ); // print Outer } }; } } 

BTW Java class names begin with uppercase by convention.

+27
Apr 28 '10 at 17:36
source share

Confirm the class name of the outer class as follows:

 outer.this 
+6
Apr 28 '10 at 17:24
source share

yes, you can use the external class name with this . outer.this

+1
Apr 28 '10 at 17:28
source share



All Articles