EFreak
EFreak

Reputation: 3289

How can objects of a nested classes access the object that they're nested in?

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

Answers (5)

Stephen C
Stephen C

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

Erik
Erik

Reputation: 91270

public outerClass getthis() {
    return outerClass.this;
}

Upvotes: 0

mdrg
mdrg

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

ftr
ftr

Reputation: 53

outerClass.this does the trick. Your class names should start with a capital letter for the sake of clarity.

Upvotes: 0

David O'Meara
David O'Meara

Reputation: 3033

outerClass.this.method()

Class name should start with a capital, it reduces confusion in cases like this one.

Upvotes: 8

Related Questions