Java Reference
In-Depth Information
< Day Day Up >
Puzzle 55: Creationism
Sometimes, it is useful for a class to keep track of how many instances have been created. This is
typically done by having its constructors increment a private static field. In the program that
follows, the Creature class demonstrates this technique, and the Creator class exercises it, printing
the number of Creature instances it has created. What does the program print?
public class Creator {
public static void main(String[] args) {
for (int i = 0; i < 100; i++)
Creature creature = new Creature();
System.out.println(Creature.numCreated());
}
}
class Creature {
private static long numCreated = 0;
public Creature() {
numCreated++;
}
public static long numCreated() {
return numCreated;
}
}
 
 
Search WWH ::




Custom Search