import java.text.DecimalFormat; public class Kitten { private static int kittenCount = 0; private static final DecimalFormat OUNCE_FORMATTER = new DecimalFormat("0.0"); private int number; private String fur; private double ounces; private boolean isFemale; /** * Makes a kitten with random gender; weight between 2 and 7 ounces; * and either tan, brown, black, white, tortiseshell, tabby, or no fur. */ public Kitten() { // count this kitten Kitten.kittenCount += 1; this.number = Kitten.kittenCount; // get a random fur color double n = Math.random(); if (n < 0.01) this.fur = "no"; else if (n < 0.1) this.fur = "tan"; else if (n < 0.2) this.fur = "brown"; else if (n < 0.4) this.fur = "black"; else if (n < 0.45) this.fur = "white"; else if (n < 0.6) this.fur = "tortiseshell"; else this.fur = "tabby"; // get a random weight this.ounces = 2 + Math.random()*5; // get a random gender this.isFemale = Math.random() >= 0.5; } /** * This method, like toString, exists in every object. The Garbage * Collector calls it right before it reclaims the memory used by * this object. */ public void finalize() { System.out.println("GC reclaiming memory for Kitten #" + this.number); } /** * @return Something like "Kitten #1234: a male kitten with tan fur weighing 4.0 ounces" */ public String toString() { String ans = "Kitten #" + this.number + ": a "; if (this.isFemale) { ans += "female"; } else { ans += "male"; } ans += " kitten with " + this.fur + " fur weighing "; ans += OUNCE_FORMATTER.format(this.ounces) + " ounces"; return ans; } }