I have created an inner class in an inner class :
public class EnclosingClass {
public class InnerClass {
private EnclosingClass getEnclosing() {
return EnclosingClass.this;
}
public class InnerInnerClass {
private InnerClass getEnclosing() {
return InnerClass.this;
}
private EnclosingClass getEnclosingOfEnclosing() {
return EnclosingClass.this;
}
}
}
}
I have been surprised that java allows the InnerInnerClass
to access directly the EnclosingClass
. How is this code implemented internally by Java?
The InnerInnerClass
keeps two pointers (one on the InnerClass
and the other on the EnclosingClass
) or the InnerInnerClass access the EnclosingClass
through the InnerClass
?
Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass. InnerClass innerObject = outerObject.
Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.
Accessing the Private Members Write an inner class in it, return the private members from a method within the inner class, say, getValue(), and finally from another class (from which you want to access the private members) call the getValue() method of the inner class.
You just need to disassemble the resulting class with javap to see what's going on:
private EnclosingClass getEnclosingOfEnclosing();
Code:
0: aload_0
1: getfield #1 // Field this$1:LEnclosingClass$InnerClass;
4: getfield #3 // Field EnclosingClass$InnerClass.this$0:LEnclosingClass;
7: areturn
So first it gets the instance of the directly enclosing class, then it gets the "top-level" enclosing class from that.
If the inner classes are not 'static', they contain references internally to the class in which they are contained.
Unless you make an inner class static, then yes, it does have a reference to the instance it exists within, and can reference it members (including private), the same goes for inner inner classes, inner inner inner classes and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With