Java-Counting the instance of a class



---TestInstanceCounter.class---

class TestInstanceCounter {
public static void main(String[] args) {
SomeClass sc1 = new SomeClass();
SomeClass sc2 = new SomeClass();

System.out.println("You have created "
+ SomeClass.countInstances()
+ " instances of "
+ "the class called \"SomeClass\"");

System.out.println("---------------------------------------------");

SomeClass sc3 = new SomeClass();
SomeClass sc4 = new SomeClass();
SomeClass sc5 = new SomeClass();

System.out.println("You have created "
+ SomeClass.countInstances()
+ " instances of the class called \"SomeClass\"");

System.out.println("---------------------------------------------");
}
}


---SomeClass.class---

class SomeClass {
/*initialized when class is loaded and all the instances of the class share the same static variable*/
private static int instanceCtr = 0;
SomeClass() {
instanceCtr++;
}
public static int countInstances() {
return instanceCtr;
}
}


Post a Comment

0 Comments