Reputation: 375
Suppose I have a class A and inner class A.B, and I create an instance of class A.B in the method of the separate class.
A obj1 = new A();
A.B obj2 = obj1.new B();
What is this instance? Is it a part of obj1 or an independent object?
As I understand some instance is the independent entity, e.g. 1 apple, 1 person etc. Whether it's possible to draw an analogy with the object of the inner class?
Upvotes: 1
Views: 87
Reputation: 5316
B objectOfB1 = objectOfA1.new B ();
B objectOfB2 = objectOfA2.new B ();
implies objectOfB1 is associated with objectOfA. objectOfB1 has an implicit reference of the object referenced by objectOfA1. Similarly objectOfB2 is associated with objectOfA2.
now even if objectOfA1 = null; is done then also the object of A that was being referenced by it will not be eligible for garbage collection as it has an hard reference from inside the object of class B I.e. objectOfB1.
objectOfB1 knows objectOfA1 but not vice versa. You can think it as if we are passing objectOfA1 as a constructor parameter to create objectOfB1. same is true for objectOfB2, it holds an implicit reference to objectOfA2.
class OuterClass{
InnerClass dataMem1;
InnerClass dataMem2;
class InnerClass{
int k;
}
}
Here Object of InnerClass can not exist without an object of OuterClass so when complied then an reference of outerClass is injected by the compiler in It.
Not exactly it happens as below but you can refer below code for your understanding as very similar thing happens when above code is complied.
class OuterClass{
InnerClass dataMem1;
InnerClass dataMem2;
}
class InnerClass{
OuterClass objInjectedByCompiler;
int k;
// constructor
InnerClass(OuterClass objectOfOuter){
this.objInjectedByCompiler = objectOfOuter;
}
}
For creating the object of InnerClass you need an Object of OuterClass.
Now Question should be how actually the InnerClass's object gets the object of OuterClass. When we do objOfOuter.new InnerClass()
then the this
associated with objOfOuter
acts as the needed object of class OuterClass.
PS: Above holds true for non static nested classes and not for inner nested classes which are static.
Upvotes: 2