Ireneusz Kordal wrote:I see only 3 objects created:
Base class is not used in this code, so it is not loaded nor initialised.
But i bet that the author of this question wanted the class Base to be extended by the class Numbers, but he accidentally "lost" the clause 'extends BaseClass'
In this case (Numbers extends BaseClass) 5 objects are created (remember that each array is an instance of Object):
saima kanwal wrote:If Numbers extends BaseClass , so when new is called on Numbers, at line 9, then 3 objects must be created (instead of two): BaseClass (as Baseclass constructor is invoked being the super class of Numbers),Numbers , and the int array in the Baseclass. so when n is set to null ( at line 11), the same 3 objects must die .
saima kanwal wrote:Basically, I am confused about the number of objects created when there is a superclass and a subclass; should we consider the superclass as a separate object created when the subclass is instantiated?
saima kanwal wrote:
Also, one more thing to be cleared: Here in this code , i feel that there is no use of line 12, because the object n is set to null at line 11 , and num points to the same object, so it is already set to null. so i think num = null (line 12)is not sending any objects to GC. am i correct or not??
BaseClass is not an 'Object', it is a 'Class'. Class is created/loaded by the class loader
on the first use of the class, and then lives on the heap until program dies (strictly speaking until class loader that holds reference to this class is unloaded
and garbage collected) ... but there are rather advanced topics and this is not covered by SCJP objectives.
On SCJP they test your knowledge only about 'Objects' creation and destroying.
Javaspec defines the object as: An object is a class instance or an array. - http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.1
So - in the context of SCJP questions related to garbage collection - do not count 'classes' as 'objects', because this gives you wrong answers.
Look at this example: