aspose file tools*
The moose likes Beginning Java and the fly likes Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Class" Watch "Inner Class" New topic
Author

Inner Class

Sivaram Ponugoti
Greenhorn

Joined: Apr 25, 2008
Posts: 3
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();
}
}
}

Thanks
Siva
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Welcome to JavaRanch!

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
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?

Thanks
Bala
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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
I'm confused! So what does InnerDemo.this refer to? Does it refer to the inner or outer class?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Sivaram Ponugoti:
I'm confused! So what does InnerDemo.this refer to? Does it refer to the inner or outer class?

Inside an instance of Inner, InnerDemo.this references the instance of InnerDemo that was used to create the instance of Inner.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Inner Class