Whenever an object is made of a class, its constructor is invoked. Whenever the constructor runs we increment the counter value. Hence number of objects created of a class equals to the counter value.
Here is the source code of the Java Program to Find Out the Number of Objects Created of a Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public class Number_Objects
static int count=0;
public static void main(String args)
Number_Objects obj1 = new Number_Objects();
Number_Objects obj2 = new Number_Objects();
Number_Objects obj3 = new Number_Objects();
Number_Objects obj4 = new Number_Objects();
System.out.println("Number of objects created:"+count);
$ javac Number_Objects.java $ java Number_Objects Number of objects created:4
Sanfoundry Global Education & Learning Series – 1000 Java Programs.