Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can "this" of the outer class be accessed from an inner class?

Is it possible to get a reference to this from within 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?       }     };   } } 
like image 367
llm Avatar asked Apr 28 '10 17:04

llm


People also ask

How do you call an outer class from an inner class?

Of your inner class is non static then create an object of innerClass. OuterClass out = new OuterClass(); OuterClass. InnerClass inn = out.

Can outer class access inner class methods?

Yes. These qualifiers will only affect the visibility of the inner class in classes that derive from the outer class. Can inner class access members of outer class? Yes, including the ones declared private , just as any instance method can.

Can inner class calling Outer method?

No, you cannot assume that the outer class holds an instance of the inner class; but that's irrelevant to the question. You're first question (whether the inner class holds an instance of the outer class) was the relevant question; but the answer is yes, always.


1 Answers

You can access the instance of the outer class like this:

Outer.this 
like image 195
Guillaume Avatar answered Oct 06 '22 01:10

Guillaume