Program to count number of objects created for class.

There are following way to count number of objects created for Class in java.

  • When we create the object of ObjectCount class. then constructor will be invoked.
  • How much time constructor will be run then we increment the count value.
  • Count value is equals to number of objects created of a class.
  • Call the totalCounter() method to print the number of object creation.
public class ObjectCount {
	static int count = 0;

	ObjectCount() {
		count += 1;
	}

	public static int totalCounter() {
		return count;
	}

	public static void main(String[] args) {
		ObjectCount a = new ObjectCount();
		ObjectCount b = new ObjectCount();
		ObjectCount c = new ObjectCount();
		ObjectCount d = new ObjectCount();
		System.out.println("total number of object creation :- " + totalCounter());
	}
}

Output :-
total number of object creation :- 4