Below is an example of Composition:
public class A3 {
B b = new B();
}
What I learned is that as soon as object of A3 is GC'ed (or becomes eligible for GC), object of B will also be GC'ed (or becomes eligible for GC).
Now, let's consider below situation, so as per my understanding after d.m1();, a3 object on heap will become eligible for GC, but I don't think that b object becomes eligible for GC.
My two understandings are contracting with each other, could someone please help me identify which one is wrong.
public class Testing {
public static void main(String[] args) {
D d = new D();
d.m1();
d.m2();
// do some more things...
}
}
public class A3 {
B b = new B();
public B getB() {
return b;
}
}
public class B{
public void m1() {
System.out.println("B.m1");
}
}
public class D{
B bd2;
public void m1() {
A3 a3 = new A3();
bd2 = a3.getB();
}
public void m2() {
bd2.m1();
}
}
UPDATE: I do understand difference between "eligible for GC" and "actually getting GC'ed", so for sake of convenience, let's say object will immediately be GC'ed once it becomes eligible.