package exampleStatic; public class CounterOfInstances { // Stores the total number of instances created. private static int numberOfInstances = 0; // Returns the total number of instances created. static int getCounter() { return numberOfInstances; } // Increases the total number of instances created. private static void addInstance() { numberOfInstances++; } // The default constructor of the class -- it is invoked whenever an // instance is created. // It calls the method that increases the total number of instances! CounterOfInstances() { CounterOfInstances.addInstance(); } // Main method public static void main(String[] args) { System.out.println("At the beginning, we have " + CounterOfInstances.getCounter() + " instances of the class."); // We create 10 new instances of the class CounterOfInstances. for (int i = 0; i < 10; i++) new CounterOfInstances(); System.out.println("We have now created " + CounterOfInstances.getCounter() + " instances of the class."); } }