Java: How to get immediate parent(who is not the top level class) from an inner class? -
i'm aware differences between static nested class , inner class in java. i'm talking inner class. i'm aware can use "outerclass.this" outer class inner class.
like directory, there 2 ways navigate: absolute , relative. example: "/aaa/bbb/ccc/ddd", if i'm inside folder "ccc" , want refer "bbb", can either: "cd /aaa/bbb" or "cd ..".
now comes java inner classes.
class aaa{ bbb b = new bbb(); class bbb{ ccc c = new ccc(); //ccc c = new ccc(b); class ccc{ //second version //bbb parent = null //ccc(bbb parent_){ // parent = parent_; //} ddd d = new ddd(); bbb getparent(){ return aaa.this.b; //i know work //or return parent; if using second version } class ddd{ } } } }
i've provided 2 versions: aaa.this.b , introduce member variable "parent", assigned value parameter of constructor.
my question: if don't introduce member variable, may use relative way immediate parent inner class? (like cd ..)
you can use bbb.this
directly refer enclosing instance of class bbb.
Comments
Post a Comment