Java examples for Object Oriented Design:Static
Use static variable to count instance
public class CountTestApp { public static void main(String[] args) {//from ww w . j a v a 2 s . c o m printCount(); for (int i = 0; i < 10; i++) { CountTest c1 = new CountTest(); printCount(); } } private static void printCount() { System.out.println("There are now " + CountTest.getInstanceCount() + " instances of the CountTest class."); } } class CountTest { private static int instanceCount = 0; public CountTest() { instanceCount++; } public static int getInstanceCount() { return instanceCount; } }