/* Monster.java example code AC Chapin */ package MonsterInherit; /** * class representing a general monster with teeth * */ public class Monster { protected int teeth; // protected means inheriting classes can use directly (and rest of package too) protected String name; protected boolean alive; /** * default constructor for Monster * */ public Monster() { teeth = 0; name = "Monster"; alive = true; } /** * copy constructor for Monster * */ public Monster(Monster original) { this(); if (original != null) { // ints and Strings are safe to just copy values // if it was an object, we'd need to make a copy of that // with clone if possible teeth = original.teeth; name = original.name; alive = original.alive; } } /** * accessor for teeth * */ public int getTeeth() { return teeth; } /** * mutator for teeth * */ public void setTeeth(int val) { teeth = val; } /** * accessor for alive alternative naming style for boolean accessor * */ public boolean isAlive() { return alive; } /** * mutator for alive * */ public void setAlive(boolean alive) { this.alive = alive; } /** * accessor for name * */ public String getName() { return name; } /** * mutator for name * */ public void setName(String name) { this.name = name; } /** * monsters eat people * */ public void eat() { System.out.println("Eat people!"); } /** * monsters make noise * */ public void roar() { System.out.println("GRRARGH!"); } /** * monsters fight!! * */ public void fight(Monster other) { if (other != null) { System.out.println(this + " and " + other + " are fighting!"); roar(); other.roar(); // 50/50 chance if (Math.random() > 0.5) { System.out.println(other + " wins"); this.alive = false; } else { System.out.println(this + " wins"); other.alive = false; } } else { System.out.println(this + " and has no one to fight!"); roar(); } } /** * fake clone method * */ public Monster clone() { return new Monster(this); } /** * overrides toString from Object * * @return string representing this monster includes Object's version of * toString for fun * */ @Override public String toString() { return name + " -- a monster with " + getTeeth() + " teeth at " + super.toString(); // user Object's toString } /** * check if equal to obj * if class has subclasses, single method equals * is safer */ public boolean equals(Object obj) { // only other monsters if (obj != null && obj instanceof Monster) { // cast to get access to vars Monster mobj = (Monster)obj; // check all vars // taking advantage of short circuit evaluation of && so no null pointer return mobj.getTeeth() == getTeeth() && mobj.alive == alive && getName() != null && getName().equals(mobj.getName()) ; } return false; } }