Question:
Is there a way to determine the number ofinstantiated objects of a certain class?
Answer:
Unfortunately, there are no methods of class Object
orClass
thattrack the number of extant instances of a certain class.
A do-it-yourself solution is to extend the class you’re interested inwith a subclass containing a static variable that keeps count of thenumber of extant instances. This variable is incremented by allconstructors and decremented by the finalize method:
Since count is a static variable, it belongs to the classclass Tank { … } // a predefined class class MyTank extends Tank { private static int count; // = # of extant instances // a typical constructor public MyTank(…) { super(…); // construct parent object count++; } // an accessor int getCount() { return count; } // called during gc public void finalize() { –count; } } // MyTank
MyTank
ratherthan instances of MyTank
. Thus, like a static variable in C, itslifetime is global (i.e. it persists until the program ends), but itsscope is restricted (to MyTank
methods).Warning: Count reflects the number of extant instances ofMyTank
. Thismay be different from the number of extant instances currently in scope.Remember, an object exists until it is recycled by the garbage collector.It’s difficult to control when this happens, and only then is thefinalize()
method called and count decremented.