public class StaticCounter {
public static void main (String [] args) {
System.out.println(CountingObject.getCount() + " objects created");
CountingObject co = new CountingObject(5);
System.out.println(CountingObject.getCount() + " objects created");
CountingObject co1 = new CountingObject(3);
System.out.println(co1.getCount() + " objects created");
co1 = co;
System.out.println(co1.getCount() + " objects created");
}
}
class CountingObject {
public int value;
private static int howmany; // private var: not accessible from outside
public CountingObject(int val) {
value = val;
++howmany;
}
// a static method:
public static int getCount() {
return howmany;
}
// what happens if getCount is not static?
}
This is an example from CSci 1211 course.