How can nested class objects access the object in which they are nested?

How to get the parent of this object from a method in an 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, for example

public OuterClass getthis() {
    return this;
}

Any other suggestions? Is there a way from Java itself?

+3
source share
5 answers
outerClass.this.method()

The class name should start with capital, this reduces confusion in cases like this.

+8
source

I think this should do it:

class outerClass {
    public outerMethod() {
         // this refers to the object in the outer class
    }
    class innerClass {
        public innerMethod() {
             // Here 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 is a blatantly bad style to declare a class with a name that does not start with a capital letter. Expect to be reminded of this again if you decide to ignore the agreement.

+2
source

outerClass.this . .

0
outerClass.this.outerMethod();

This obviously does not work on static inner classes since there is no outer instance of the outer class.

And before I forget, read the Java Code Conventions . CLASS must begin with capital letters.

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

Source: https://habr.com/ru/post/1792185/


All Articles