How to Find Number of Objects Created in JavaIn Java, when we create an object of the class, the constructor of the class is always called, by default. We can count the number of objects directly if we keep tracking how many times the constructor is called. In this section, we will learn how to count the number of objects. In order to count the number of objects, we need to add a count variable in the constructor and increments its value by 1 for each invocation. Remember that the variable count must a class-level variable. Now, the problem is that class-level variables have different values for each object, then how the value will be updated? So, declare the variable (count) as static. The reason to make the variable static is that the static variable has only a copy per class that is shared by all objects of the class. By declaring the variable as static, all objects update the value of the variable. Let's implement the logic in a Java program. CountObject.java Output: Total Number of Objects: 5 The above program can also be written as follows: ObjectCount.java Output: Total Number of Objects: 3 Let's Create another Java program for the same. EmployeeDemo.java Output: There are 4 objects in this class. |