public class StaticCounter {
    public static void main (String [] args) {
	System.out.println(CountingObject.howmany + " objects created");

	CountingObject co = new CountingObject(5);
	System.out.println(CountingObject.howmany + " objects created");

	CountingObject co1 = new CountingObject(3);
	System.out.println(co1.howmany + " objects created");

	co1 = co;
	System.out.println(co1.howmany + " objects created");

	// cheating: setting the counter to 5 
	// (can do it, because it's public)
	co.howmany = 5;
	System.out.println(CountingObject.howmany + " objects created");
    }
    
}

class CountingObject {
    public int value;
    public static int howmany; // the counter of the number of objects

    public CountingObject(int val) {
	value = val;
	++howmany;
    }
}


This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.