You can track the number of objects created in Java using a static counter variable within your class. Here's how:
-
Declare a Static Counter:
- Inside your class, declare a static variable of type
int
to keep track of the object count. - Initialize it to 0.
public class MyClass { private static int objectCount = 0;
- Inside your class, declare a static variable of type
-
Increment the Counter in the Constructor:
- In the class's constructor, increment the
objectCount
variable by 1.
public MyClass() { objectCount++; }
- In the class's constructor, increment the
-
Create a Getter Method:
- Create a static method to return the current value of
objectCount
.
public static int getObjectCount() { return objectCount; }
- Create a static method to return the current value of
-
Print the Object Count:
- Call the
getObjectCount()
method to retrieve the object count and print it.
public static void main(String[] args) { MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(); System.out.println("Number of objects created: " + MyClass.getObjectCount()); }
- Call the
Example:
public class MyClass {
private static int objectCount = 0;
public MyClass() {
objectCount++;
}
public static int getObjectCount() {
return objectCount;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println("Number of objects created: " + MyClass.getObjectCount()); // Output: 2
}
}
This approach provides a simple way to track the number of objects created for a specific class in your Java program.