How to Count the Number of Instances of a Class in Java?
These tutorials provide a concise guide on counting the number of instances/objects of a class in Java.
In Java, an object of a class can be created using the new keyword. An object is essentially an instance of a class. It’s important to note that a class can have multiple objects.
So, how do you count the number of objects/instances of a class in Java?
The keyword static
provides a global scope that can be created and accessed by all objects of a class. A static
member variable is commonly used to keep track of the count.
Here’s a step-by-step guide to counting:
- In a class, create a
static
variable (objectCount). All objects have access to this variable; these are referred to asclass scope variables
. - Initialize
objectCount
with zero initially. - Static variables can only be accessed by static members directly.
- Define an instance block and increment its value by one whenever a new object is created.
- Decrement
objectCount
in thefinalize
method, which is called whenever an object is ready for garbage collection. This is useful for counting non-garbage-collected objects. - Finally, print the static member variable using the class.
This can be be achieved using in two approaches
- instance block
- constructor block
Count an objects using instance block
Now, let’s consider an example using an instance block
for better clarity.
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--;
}
}
The constructor contains code to increment the object count.
The process of destruction
using the finalize
method includes code for decrementing the object count.
Count an objects using constructor block
The same example can be expressed by incrementing objectCount
in the constructor block.
In this case, static member variables are incremented within the constructor. The constructor is invoked whenever a 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 programs return the following output
Object Count 2
Conclusion
As mentioned earlier, static member variables have class scope. The counting of instances can be achieved through either an instance block or a constructor approach.
Hope you like this post.