How to count total number of class objects created in Java
This example will help you to understand how to count the total number of class objects created in Java.
1. Create a global static variable of type int
in the class.
2. Define the constructor of the class.
3. Increase the value of the variable in the constructor.
Department.java
package org.websparrow;
public class Department {
private static int noOfObjects;
public Department() {
noOfObjects++;
}
public static void main(String[] args) {
Department d1 = new Department();
Department d2 = new Department();
Department d3 = new Department();
System.out.println("Total objects created: " + noOfObjects);
}
}
Output:
Total objects created: 3