How to count the number of objects of a class in java

Suppose you want to know how many objects of a class have been created during a program execution. How would you do that?


Using constructor

When an object of a class is created, its constructor is always called. Thus, if we keep track of how many times the constructor of a class is called, we directly know number of its objects that have been created.
Thus, we need to add some counter in a constructor and increment its value by 1 in every invocation. This counter should be a class level variable.
Since class level variables have different values for each object, we have to make this variable as static. This is because static variables have only one copy per class and are shared by all objects of the class.
So if the counter variable is kept static, all objects will increment the value of same variable.
Example,

public class ObjectCounter {
   // static variable to keep track of objects
   private static int counter;

   /*
   * Constructor
   */
   public ObjectCounter() {
      // increase the count
      counter++;
   }

   public static void main(String[] args) {
      // create objects
      ObjectCounter objectOne = new ObjectCounter();
      ObjectCounter objectTwo = new ObjectCounter();
      ObjectCounter objectThree = new ObjectCounter();
      System.out.print("Total objects: " + ObjectCounter.counter);
   }
}

Above code declares a static field counter to keep track of the number of objects of this class. This field is incremented inside the constructor.

It creates 3 objects and every time an object is created, the counter is incremented so that after 3 objects created, the count will be 3.
If counter is not kept static, then every object will have its own copy of counter and it will always be 1. Also, in that case it can not be accessed using class name directly.
Output of above program will be

Total objects: 3

Hope you liked this post. Do not forget to click the clap below to show your love.

Leave a Reply