Use static variable to count instance - Java Object Oriented Design

Java examples for Object Oriented Design:Static

Description

Use static variable to count instance

Demo Code

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;
    }
}

Related Tutorials