Let me break this line by line:
CardBoard c1 = new CardBoard();
Now we have two objects: CardBoard
c1
point and Short
c1.story
. For GC, there are no c1
points in the CardBoard
and story
points of CardBoard
in Short
...
CardBoard c2 = new CardBoard();
As above, we now have four objects, none of which are available to the GC.
CardBoard c3 = c1.go(c2);
We call the method on the CardBoard that c1
points to, passing the value of c2
, which is a reference to the CardBoard
object. We reset the parameter, but Java is passed by value, which means that the c2
variable itself is not affected. Then we return a null parameter. c3
null
, c1
and c2
are unaffected. We still have 4 objects, none of which can be GC'd.
c1 = null;
We have null c1
. The CardBoard
object that c1
previously pointed to now no longer points to it, and it could be GC'd. Since the story
variable inside this CardBoard
object is the only thing pointing to Short
, and since this CardBoard
object is eligible for GC, Short
also becomes suitable for GC. This gives us 4 objects, 2 of which can be GC'd. Objects suitable for the GC are those previously referenced by c1
and c1.story
.
source share