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:
class 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 Since count is a static variable, it belongs to the classMyTank 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.
Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.























