Reputation: 3289
How do I get the parent this object from a method in the inner class?
class OuterClass {
public outerMethod() {
// this refers to the object in the outer class
}
class InnerClass {
public innerMethod() {
// this refers to the object in the inner class
// How do I get my current parent object
}
}
}
One way is to add a method like
public OuterClass getthis() {
return this;
}
Any other suggestions? Is there a way from java itself ?
Upvotes: 3
Views: 1376
Reputation: 718886
I think this should do it:
class outerClass {
public outerMethod() {
// this refers to the object in the outer class
}
class innerClass {
public innerMethod() {
// Here's how to get and use the parent class reference
outerClass daddy = outerClass.this;
daddy.outerMethod();
// However, you can also just call the method, and
// the "outer this" will be used.
outerMethod();
}
}
}
BTW - it is egregiously bad style to declare a class with a name that doesn't start with a capital letter. Expect to be reminded of this, repeatedly, if you choose to ignore the conventions.
Upvotes: 2
Reputation: 3402
outerClass.this.outerMethod();
This obviously does not work on static inner classes, as there is no enclosing instance of the outer class.
And before I forget, read the Java Code Conventions. CLass should start with uppercase letters.
Upvotes: 0
Reputation: 53
outerClass.this
does the trick. Your class names should start with a capital letter for the sake of clarity.
Upvotes: 0
Reputation: 3033
outerClass.this.method()
Class name should start with a capital, it reduces confusion in cases like this one.
Upvotes: 8