/** * Exam example: a simple model of a dog * * @author CSC 142 * */ public class Dog { private String name; private boolean isHungry; private String lastFood; private int count; // maximum number of times the dog plays before getting hungry // final means constant // can be made public since it can't be changed // static means shared by all objects (the constant doesn't belong // to a specific object. The constant belongs to the class). public static final int MAX_TIMES = 5; /** * Creates a dog given its name. Initially the dog is hungry. * * @param name * the name of the dog. */ public Dog(String name) { this.name = name; this.isHungry = true; } /** * Feeds the dog * * @param food * the food given to the dog * @return true if the dog eats, and false if not */ public boolean eat(String food) { if (isHungry) { if (!food.equals(lastFood)) { // not (food != lastFood) { System.out.println("Yummy"); isHungry = false; lastFood = food; count = 0; return true; } else { System.out.println("Not the same thing again!"); return false; } } else { System.out.println("Thank you. I am not hungry."); return false; } } /** * Makes the dog play fetch. The dog plays fetch only if it is not hungry. */ public void fetch() { if (count == MAX_TIMES) { isHungry = true; } if (!isHungry) { System.out.println("I love to play fetch."); count++; } else { System.out.println("I am too hungry to play."); } } /** * Makes the dog roll over. The dog rolls over only if it is not hungry. */ public void rollOver() { if (count == MAX_TIMES) { isHungry = true; } if (!isHungry) { System.out.println("I love to roll over."); count++; } else { System.out.println("I am too hungry to play."); } } }