Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Mar 20, 1997

Determining the Number of Instantiated Objects in Class

Question:
Is there a way to determine the number of instantiated objects of a certain class?

Answer:
Unfortunately, there are no methods of class Object or Class that track the number of extant instances of a certain class.

A do-it-yourself solution is to extend the class you're interested in with a subclass containing a static variable that keeps count of the number of extant instances. This variable is incremented by all constructors 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 class MyTank rather than instances of MyTank. Thus, like a static variable in C, its lifetime is global (i.e. it persists until the program ends), but its scope is restricted (to MyTank methods).

Warning: Count reflects the number of extant instances of MyTank. This may 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 the finalize() method called and count decremented.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date