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


This is an short tutorials on how to count number of instances/objects of a class in java. Instance/object count in java with example

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

A class can have multiple objects.

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

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

Here is an step by step guide to count.

  • In a class, created a static variable(objectCount), 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 new object is created
  • objectCount decremented in finalize method, which is called whenever object is ready for garbage collection. This will be useful to count non garbage collected objects.
  • Finally printed the static member variable using an 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--;
    }
}

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 variable are incremented in constructor, Constructor are called whenever 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 both programs return the following output

Object Count 2

Conclusion

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

Hope you like this post.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.