|
Question 17.1: Study the following code:
class AnimalTest begin private function void chatter(Animal[] a) begin for (var int i=0; i<a.length; i=i+1) begin a[i].talk(); end end beginMain var Animal[] farm = { new Dog(), new Cow(), new Fish() }; var Animal[] ark = { new Dog(), new Dog(), new Cow(), new Cow(), new Fish(), new Fish() }; var Cow[] herd = { new Cow(), new Cow(), new Cow() }; chatter(farm); chatter(ark); chatter(herd); endMain end class Animal begin method boolean breathesUnderwater() begin return false; end method boolean isPredator() begin return false; end method void talk() begin end end class Dog extends Animal begin method boolean isPredator() begin return true; end method void talk() begin System.out.println("Woof woof!"); end end
Question 17.2: Write the following classes that subclass the Animal class above: Cow, Cat, Fish, and Whale.
Question 17.3: Write the Shark class which extends Fish class. Override all necessary methods. For the sake of this example and the code that follows, suppose that shark's talk method prints out "Chomp Chomp!".
Question 17.4: Run the AnimalTest class to make sure that all the methods work correctly.
Question 17.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 a array. Here is some code to get you started:
private function void chatter(Animal[] a) begin for (var int i=0; i<a.length; i=i+1) begin if (a[i] instanceof Cow) then begin System.out.println("Moo!"); end else if (a[i] instanceof Cat) then begin System.out.println("Meow!"); end /* other code goes here */ end end
Note that the sub-classes must appear before super-classes in the above code, otherwise the wrong message will be printed out for sub-classes.
Question 17.6: Why is the code from the last question not as good as calling each animal's talk method?
Back to J.T.W |
This page has the following hit count:
|