Use static field to do Instance Count - Java Object Oriented Design

Java examples for Object Oriented Design:Static

Description

Use static field to do Instance Count

Demo Code

public class Main {
    private static int numInstances = 0;

    protected static int getCount() {
        return numInstances;
    }/*w ww .j a v  a  2  s  .com*/

    private static void addInstance() {
        numInstances++;
    }

    Main() {
        Main.addInstance();
    }

    public static void main(String[] arguments) {
        System.out.println("Starting with " +
            Main.getCount() + " objects");
        for (int  i = 0; i < 500; ++i)
            new Main();
        System.out.println("Created " +
            Main.getCount() + " objects");
    }
}

Result


Related Tutorials