/** * class to test out Monster and its children w/ polymorphism **/ package MonsterInherit; public class MonsterTestHarness { /** * have two monsters mash it up **/ public static void monsterMash(Monster m1, Monster m2) { System.out.println("\nNow is the time on Sprockets when monsters fight!"); // only let them fight if they are not equal if (!m1.equals(m2)) { m1.fight(m2); } else { System.out.println("Hey! [" + m1 + "] and [" + m2 + "] are the same guy!"); System.out.println("I won't let a monster fight itself!"); } } /** * create a bunch of monsters of different types * in an array of Monster **/ public static Monster [] makeMonsters() { Monster m = new Monster(); m.setTeeth(5); VampireBat v = new VampireBat(); MuppetMonster p = new MuppetMonster(); p.setMySong("Ob la di, ob la da..."); Monster [] mlist = new Monster[10]; mlist[0] = m; mlist[1] = v; mlist[2] = p; mlist[3] = new MuppetMonster(); mlist[4] = new VampireBat(); // rest of monsters with types chosen randomly int r = 0; for (int i = 5; i < mlist.length; i++) { r = (int)(Math.random() * 3); if (r == 0) { mlist[i] = new Monster(); // random number of teeth mlist[i].setTeeth((int)(Math.random() * 201)); } else if (r == 1) { mlist[i] = new MuppetMonster(); // ((MuppetMonster)mlist[i]) casts back to the MuppetMonster type // and evaluates to the address of a MuppetMonster // so we can use a MuppetMonster-only method ((MuppetMonster)mlist[i]).setMySong("Song " + i); } else { mlist[i] = new VampireBat(); } } return mlist; } /** * main method demonstrating use of monsters * and inheritors **/ public static void main(String [] args) { // set up the array Monster [] mlist = makeMonsters(); // each monster fights next in the array (last fights first) for (int i = 0; i < mlist.length; i++) { monsterMash(mlist[i], mlist[(i+1)%mlist.length]); } } }