
m4_changequote(,)

BO(Question 4.17.1:) Study, compile and run the following code:

@example
CLASS AnimalTest
BEGIN
PD PRIVATE FUNCTION void chatter(Animal[] a)
PD BEGIN
PD PD SUPERFOR (VAR int i=0 TU a.length-1)
PD PD BEGIN
PD PD PD a[i].talk();
PD PD END
PD END
PD BEGINMAIN
PD PD VAR Animal[] farm = @{ new Dog(), new Cow(), new Fish() @};
PD PD VAR Animal[] ark  = @{ new Dog(), new Dog(), new Cow(), new Cow(), new Fish(), new Fish() @};
PD PD VAR Cow[]    herd = @{ new Cow(), new Cow(), new Cow() @};
PD PD chatter(farm);
PD PD chatter(ark);
PD PD chatter(herd);
PD ENDMAIN
END

CLASS Animal
BEGIN
PD METHOD boolean breathesUnderwater()
PD BEGIN
PD PD RETURN FALSE;
PD END

PD METHOD boolean isPredator()
PD BEGIN
PD PD RETURN FALSE;
PD END

PD METHOD void talk()
PD BEGIN
PD END
END

CLASS Dog EXTENDS Animal
BEGIN
PD METHOD boolean isPredator()
PD BEGIN
PD PD RETURN TRUE;
PD END

PD METHOD void talk()
PD BEGIN
PD PD System.out.println("Woof woof!");
PD END
END
@end example

BO(Question 4.17.2:) Write the following classes that subclass the Animal
class above: TT(Cow), TT(Cat), TT(Fish), and TT(Whale).

@cindex Writing your own classes

BO(Question 4.17.3:) Write the TT(Shark) CLASS which extends TT(Fish)
CLASS. Override all necessary methods. For the sake of this example
and the code that follows, suppose that shark's TT(talk) METHOD prints out
"Chomp Chomp!".

@cindex Polymorphism

BO(Question 4.17.4:) Run the TT(AnimalTest) class to make sure that all the
methods work correctly.

BO(Question 4.17.5:) Rewrite the chatter method so that it never calls the
talk methods and instead uses a series of IF (DOTS) THEN DOTS
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:

@cindex Arrays
@cindex Arrays of TT(Object) type

@example
PRIVATE FUNCTION void chatter(Animal[] a)
BEGIN
PD SUPERFOR (VAR int i=0 TU a.length-1)
PD BEGIN
PD PD IF (a[i] instanceof Cow) THEN
PD PD BEGIN
PD PD PD System.out.println("Moo!");
PD PD END
PD PD ELSEIF (a[i] instanceof Cat) THEN
PD PD BEGIN
PD PD PD System.out.println("Meow!");
PD PD END
PD PD COMM(/* other code goes here */)
PD END
END
@end example

NI()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.

BO(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.

@cindex Polymorphism versus run-time type inquiry
@cindex Run-time type inquiry versus Polymorphism
@cindex Why it is better to use polymorphism rather than run-time type inquiry

m4_changequote([,])
