I have a question about accessing outer class method inside Inner class. In the below sample code I have method meth() in both outer and inner class. So how can I access outer meth() inside Inner class method meth()?
public class InnerDemo { int outerx; void meth(){ Inner obj = new Inner(); obj.meth(); } class Inner{ void meth(){ meth(); } } }
Inside an inner class, you can reference the enclosing instance by the class name followed by "this." In this example, that would be "InnerDemo.this." So calling the method would be...
InnerDemo.this.meth();
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Sivaram Ponugoti
Greenhorn
Joined: Apr 25, 2008
Posts: 3
posted
0
I got it Marc. Thank you. So If I want to access meth() in Inner Class, I need to say InnerDemo.Inner.this.meth(), right? But is this the static or non static way of calling method in Inner Classes as we are using class name?
No, this syntax only works in one direction: From the inner to the outer.
Any instance of an inner class must be associated with an instance of the enclosing class. So within an instance of an inner class, "EnclosingClass.this" has meaning, because there is only one "this" from the perspective of the inner instance.
On the other hand, there might be several different instances of the inner class for any one instance of the enclosing class. So from the enclosing class, you need to reference an inner class instance through a reference variable. For example...
Inner i1 = new Inner(); i1.meth();
Sivaram Ponugoti
Greenhorn
Joined: Apr 25, 2008
Posts: 3
posted
0
I'm confused! So what does InnerDemo.this refer to? Does it refer to the inner or outer class?