How to count the number of instances of a class in java?

These are short tutorials on how to count the number of instances/objects of a class in java.

An object of a class can be created using a new keyword in java. an object is an instance of a class.

A class can have multiple objects.

How do you count the number of objects/instances of a class in java?

static is the global scope that can be created and accessed by all objects of a class. So static member variable is used to know the count.

Here is a step-by-step guide to counting.

  • In a class, created a static variable(objectCount), and all object has access to it, These are called `class scope variables
  • objectCount is initialized with zero initially
  • Static variables are only accessed by static members directly
  • Instance block defined and incremented its value by one whenever a new object is created.
  • objectCount decremented in the finalize method, which calls whenever an object is ready for garbage collection. It is useful to count non-garbage collected objects.
  • Finally, printed the static member variable using a class.

Here is an example using instance block


public class Main
{
    private static int objectCount = 0;

    {
        objectCount += 1;
    }
    public static void main(String[] args) {
        Main t1 = new Main();
        Main t2 = new Main();
        System.out.println("Object Count "+getObjectCount());

    }
      public static  int getObjectCount(){
        return objectCount;
    }
     protected void finalize() throws Throwable{
      super.finalize();
        objectCount--;
    }
}

The constructor has a code for incrementing the object count

Destruction using finalize has a code for decrementing the object count

The same example can be rewritten with increment objectCount in constructor block

In this, static member variables are incremented in the constructor, Constructor is called whenever a new object is created.

public class Main
{
    private static int objectCount = 0;

   public MyClass() {
        objectCount++;
    }
    public static void main(String[] args) {
        Main t1 = new Main();
        Main t2 = new Main();
        System.out.println("Object Count "+getObjectCount());

    }
    public static  int getObjectCount(){
        return objectCount;
    }
     protected void finalize() throws Throwable{
      super.finalize();
        objectCount--;
    }
}

The above programs return the following output

Object Count 2

Conclusion

From above, static member variables are class scope, the instance can be counted in either instance block or constructor approach.

Hope you like this post.