Can anyone tell me how to count the number of instances of a class?
Here\'s my code
public class Bicycle {
//instance variables
public int
Since static variables initialized only once, and they're shared between all instances, you can:
class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
Read more about static fields in the JLS - 8.3.1.1. static Fields:
If a field is declared
static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. Astaticfield, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
Note that counter is implicitly set to zero