Next: Tutorial 18 Advanced J.T.W., Previous: Tutorial 16 More inheritance, Up: J.T.W. Tutorials [Contents][Index]
Question 4.17.1: Study, compile and run the following code:
classAnimalTestbeginprivatefunctionvoid chatter(Animal[] a)beginsuperfor(varint i=0toa.length-1)begina[i].talk();endendbeginMainvarAnimal[] farm = { new Dog(), new Cow(), new Fish() };varAnimal[] ark = { new Dog(), new Dog(), new Cow(), new Cow(), new Fish(), new Fish() };varCow[] herd = { new Cow(), new Cow(), new Cow() }; chatter(farm); chatter(ark); chatter(herd);endMainendclassAnimalbeginmethodboolean breathesUnderwater()beginreturnfalse;endmethodboolean isPredator()beginreturnfalse;endmethodvoid talk()beginendendclassDogextendsAnimalbeginmethodboolean isPredator()beginreturntrue;endmethodvoid talk()beginSystem.out.println("Woof woof!");endend
Question 4.17.2: Write the following classes that subclass the Animal
class above: Cow, Cat, Fish, and Whale.
Question 4.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 4.17.4: Run the AnimalTest class to make sure that all the
methods work correctly.
Question 4.17.5: Rewrite the chatter method so that it never calls the
talk methods and instead uses a series of if (...) then ...
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:
privatefunctionvoid chatter(Animal[] a)beginsuperfor(varint i=0toa.length-1)beginif(a[i] instanceof Cow)thenbeginSystem.out.println("Moo!");endelseif(a[i] instanceof Cat)thenbeginSystem.out.println("Meow!");end/* other code goes here */endend
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 4.17.6: Why is the code from the last question not as good as calling each animal’s talk method? In general polymorphism is preferable to run-time type inquiry.
Next: Tutorial 18 Advanced J.T.W., Previous: Tutorial 16 More inheritance, Up: J.T.W. Tutorials [Contents][Index]