O. Ziggy wrote:
Eric Kizaki wrote:Question 1 is a bit different because in creating a CardBoard a Short is initialized by setting it to 200 (object created). For question 11, the Beta b2 is not initialized (defaults to null/no new object is created). The static beta b1 is also default null (no new object created). Creating an Alpha creates only one Object that has one null reference that is shared among all the Alphas and its own null reference b2.
This is how I see the problem:
At line 11, 4 objects have been created: b1 pointing to Beta, b2 pointing to another Beta, a1 pointing to an Alpha (which has no objects just null variables), and a2 pointing to another Alpha (which has no objects just null variables).
The null a1.b1 points to the existing Beta b1 points to. Since this is a static variable it also sets a2.b1 to the existing Beta b1 points to.
The null a1.b2 point to the existing Beta b1 points to.
The null a2.b2 points to the existing Beta b2 points to.
Reference variables a1, b1, b2 are set to null.
The only external reference left is a2 (One object). Which has two references. a2.b1 still points to the object b1 used to point to (saved object). a2.b2 still points to the object b2 used to point to (saved object). The only object that is GC is the object a1 used to point to (no external references). Of the original 4 objects, only 1 is GC.
Brilliant explanation. I spent ages trying to understand this question but you've nailed it!
I was not sure about this bit in your explanation:
I didnt know that a static variable will be initialised implicitly even if the code does not initialise it so i wrote a simple code bit to test it.
The output to the above is
So it does look like a2.a was initialised implicitly even though the code did not explicitly initialise it.