/* MuppetMonster.java example code AC Chapin */ package MonsterInherit; /** * class representing a Muppet Monster * */ public class MuppetMonster extends Monster { private String mySong; // instance var for this class not in Monster private Monster friend; /** * default constructor for MuppetMonster * */ public MuppetMonster() { super(); teeth = 0; // muppets don't have teeth mySong = "La la la la la"; friend = null; // just being explicit about no infinite recursion } /** * copy constructor for MuppetMonster * */ public MuppetMonster(MuppetMonster original) { super(original); if (original != null) { mySong = original.mySong; if (original.friend != null) { // we don't know which subclass // so use clone friend = original.friend.clone(); } } else { mySong = "I ain't got nobody!"; } } /** * MuppetMonsters eat cookies overrides eat from Monster * */ public void eat() { System.out.println("C is for cookie, and cookie is for me!"); } /** * MuppetMonsters can sing * */ public void sing() { System.out.println("I sing " + getMySong()); } /** * MuppetMonsters don't roar * */ public void roar() { // do nothing } /** * MuppetMonsters don't fight!! * */ public void fight(Monster other) { System.out.println(other + " may fight with " + this + ", but nice MuppetMonsters won't fight back."); } /** * fake clone method * */ public MuppetMonster clone() { return new MuppetMonster(this); } /** * overrides toString from Monster * * @return string representing this MuppetMonster * */ public String toString() { return "muppet monster who likes to sing " + getMySong(); } /** * check if equal to obj * */ public boolean equals(Object obj) { // superclass equals checks for nulls and other vars // if we get that far, check for only other MuppetMonsters if (super.equals(obj) && obj instanceof MuppetMonster) { // cast to get access to vars MuppetMonster mobj = (MuppetMonster)obj; // check own var // taking advantage of short circuit evaluation of && so no null pointer return getMySong() != null && getMySong().equals(mobj.getMySong()); } return false; } /* accessors and mutators */ public String getMySong() { return mySong; } public void setMySong(String val) { mySong = val; } public Monster getFriend() { return friend; } public void setFriend(Monster friend) { this.friend = friend; } }