We use the static keyword when we want all the objects to share a single variable.
// jamesprogram.java class jamesprogram { public static void main (String[] args){ cat member1 = new cat("Emma", "Smith"); cat member2 = new cat("Larry", "Oldman"); cat member3 = new cat("Bob", "Timpy"); } }
//cat.java public class cat { private String first; private String last; // every object SHARES the same variable, // if you change a static variable, you change // it for ALL objects private static int members = 0; // constructor public cat (String fn, String ln){ first=fn; last=ln; members++; System.out.printf("Constructor for %s %s, members in the club: %d\n", first, last, members); } }
In this program we make 3 new objects that all share the static int variable members. Which counts upwards each time it is called. This outputs:
Constructor for Emma Smith, members in the club: 1
Constructor for Larry Oldman, members in the club: 2
Constructor for Bob Timpy, members in the club: 3