Transferring this to an answer, because the comment became too long.
What does happen?
Firstly, @Shadab is right. Object a3
will be collected while object b
remains.
Intuitive explanation
Your confusion seems to stem from the object oriented view towards the problem.
Basically you view A
as a car and b
as one of its wheels. So when looking at the problem like this the logical question is - when I crush the car and it is then gone, how can the wheel that is part of the car still exist? That does not make sense on first glance, even if someone else was given "access" to the wheel.
This is not how it works w.r.t memory management and it is also where the metaphor will break:
- When you create a car
A
it does also create a wheel B
.
- Both of these things exist independently in memory.
- The object oriented metaphor breaks here, because the objects that make up a car and which were constructed when the car was constructed are not actually "part" of the car. Only references to those objects are part of the car, but the data itself is not.
Overstretching the metaphor
If you want to have some sort of mental image of what is really going on, you can try and look at it like this:
- Let
A
be a car.
- Let
B
be a wheel
- Let
C
be a bolt
- A wheel
B
"consists" of five bolts C
, i.e. five objects C
are members of an object B
- A car
A
"consists" of four wheels B
, i.e. four objects B
are members of an object A
.
When you create A
A a = new A();
You also create four instances of B
and these in turn create twenty instances of C
. However with regard to objects in memory, your wheels are not mounted on your car with the bolts. The car A
is lying in the parking lot (which is your memory) with four postcards (references) of its wheels inside it. The four wheels are also lying somewhere else in the parking lot, each with five postcards of their respective bolts on top of them. And the twenty bolts are lying somewhere in the parking lot as well.
Maybe at this point you start to see, why this object oriented approach is not necessarily suitable to understand the way this memory management works and how the metaphor is stretched really thin.
So what happens now if you destroy the car in the parking lot? The car A
is gone, the postcards of the four wheels B
are gone too. But that does not mean that the wheels are destroyed as well. Only if in the entire parking lot the GC cannot find anything that has a postcard of a specific wheel instance it is allowed to destroy the wheel as well. But if there is another object that holds these postcards, then the wheels are not garbage collected. Same goes for the bolts.
Bottom line
Objects do not hold objects. Objects hold references to objects. Objects are only garbage collected if there is no further reference to them. Data wise these things are independent of each other, even if the OOP model may suggest otherwise when looking at it naively.