/* Bunny.java example code AC Chapin */ package cis214c04classmethods; /** * a class representing a Bunny rabbit * example of constructors, accessors, mutators */ public class Bunny { // variables are private private String name; private int carrotCount; // how many carrots { // initializer block // automatically included in all constructors // (just so we have example) setName("Unnamed Bunny"); } /** * no-parameter constructor setting default values */ public Bunny() { // includes initializer block here // sometimes explicitly put in assignment even to default value // just to emphasize we didn't forget an instance var setCarrotCount(0); } /** * parameterized constructor (name) * @param nameVal name for new bunny */ public Bunny(String nameVal) { // includes initializer block here // make sure we have workable default values this(); // using mutators inside the class for verification // of values passed in setName(nameVal); // compiler may warn that this methods is not final // but we don't know about final yet, so ignore it // leaving carrots alone } /** * parameterized constructor (all instance vars) * @param nameVal name for new bunny * @param carrotVal how many carrots should it start with */ public Bunny(String nameVal, int carrotVal) { // chaining constructors // we already have one that knows how to handle names this(nameVal); // using mutators inside the class for verification // of values passed in setCarrotCount(carrotVal); } /** * name accessor * @return the bunny's name */ public String getName() { return name; } /** * name mutator * @param val new name */ public void setName(String val) { name = val; } /** * carrotCount accessor * @return */ public int getCarrotCount() { return carrotCount; } /** * carrotCount mutator * validates to maintain 0 or positive vals * @param val */ public void setCarrotCount(int val) { // standard conditional if // in parentheses, any boolean expression if (val >= 0) { carrotCount = val; } // if we get a bad value, do nothing // and don't complain about it } /** * print a greeting */ public void sayHi() { System.out.println("My name is " + getName()); } /** * increase the number of carrots * @param numcarrots */ public void feed(int numcarrots) { setCarrotCount(getCarrotCount() + numcarrots); System.out.println("Thanks! I now have " + getCarrotCount() + " nummy carrots!"); } /** * bunny hop * the height bunnies hop * is determined by how many carrots they ate */ public void hop() { int height = getCarrotCount() / 2; System.out.println(getName() + " just hopped " + height + " feet in the air!"); } /** * toString determines how Bunny is printed * @return e.g. Fluffy, a bunny who has eaten 16 carrots */ @Override public String toString() { return getName() + ", a bunny who has eaten " + getCarrotCount() + " carrots"; } }