package guiexample; // a class representing a Bunny rabbit public class Bunny { private String name; private int carrotCount; // how many carrots private BunnyGUI myUI; // default constructor public Bunny() { name = "Unnamed Bunny"; carrotCount = 0; } // parameterized constructor (all instance vars) public Bunny(String nameVal, int carrotVal) { setName(nameVal); setCarrotCount(carrotVal); } // name accessor public String getName() { return name; } // name mutator public void setName(String val) { name = val; } // carrotCount accessor public int getCarrotCount() { return carrotCount; } // carrotCount mutator -- 0 or positive vals public void setCarrotCount(int val) { if (val >= 0) { carrotCount = val; } } public BunnyGUI getMyUI() { return myUI; } public void setMyUI(BunnyGUI myUI) { this.myUI = myUI; } // output either using an interface class // or on command line private void messageToUser(String str) { if (myUI != null) { myUI.messageToUser(str); } else { System.out.println(str); } } // print a greeting public void sayHi() { messageToUser("My name is " + getName()); } // increase the number of carrots public void feed(int numcarrots) { setCarrotCount(getCarrotCount() + numcarrots); messageToUser("Thanks! I now have " + getCarrotCount() + " nummy carrots!"); } // the height bunnies hop // is determined by how many carrots they ate public void hop() { int height = getCarrotCount() / 2; messageToUser(getName() + " just hopped " + height + " feet in the air!"); } // toString determines how Bunny is printed public String toString() { return getName() + ", a bunny who has eaten " + getCarrotCount() + " carrots"; } }