// ANSWERS: // // (1) Write the class Cow which extends class Animal. Override all // necessary methods. // // HINT: Look at how class Dog inherits from class Animal and // follow the pattern. // class Cow extends Animal { public void talk() { System.out.println("Moo!"); } } // // (2) Write the class Bird which extends class Animal. Override all // necessary methods. // class Bird extends Animal { public boolean hasWings() { return true; } public boolean canFly() { return true; } public void talk() { System.out.println("Tweet tweet!"); } } // // (3) Write the class Kiwi which extends class Bird. Override all // necessary methods. // class Kiwi extends Bird { public boolean canFly() { return false; } public void talk() { System.out.println("Kiiiii-wiiii!"); } } // // (4) Run the AnimalTest class to make sure that all the methods // work correctly. // // (5) Rewrite the chatter method so that it never calls the // talk methods and instead uses a series of "if" statements // and the "instanceof" operator to test the run-time type // of each object in the array "a". // public void chatter(Animal[] a) { // Note that the subclasses must appear // before superclasses in the following // list, otherwise the wrong message will // be printed out for subclasses. for (int i=0; i<a.length; i++) { if (a[i] instanceof Kiwi) { System.out.println("Kiiiii-wiiii!"); } else if (a[i] instanceof Bird) { System.out.println("Tweet tweet!"); } else if (a[i] instanceof Dog) { System.out.println("Woof woof"); } else if (a[i] instanceof Cow) { System.out.println("Moo!"); } else { /* it must be an Animal */ } } } //