S.J.S. tutorial 17: arrays, inheritance and polymorphism
SECTION(17, Tutorial 17)
m5_question(BO(Question 17.1:) Study the following code:
m4_begin_indent
NU()CLASS CLSS(AnimalTest) EOL
BEGIN EOL
PD PRIVATE FUNCTION VOID FUNC(chatter)(CLSS(Animal)[] VARI(a)) EOL
PD BEGIN EOL
PD PD FUR (VAR INT VARI(i)=NUMB(0); LT(i,a.length); i=i+NUMB(1)) EOL
PD PD BEGIN EOL
PD PD PD a[i].talk(); EOL
PD PD END EOL
PD END EOL
PD BEGIN_MAIN EOL
PD PD VAR CLSS(Animal)[] VARI(farm) = SQU NEW DOG(), NEW COW(), NEW FISH() GLY; EOL
PD PD VAR CLSS(Animal)[] VARI(ark) = SQU NEW DOG(), NEW DOG(), NEW COW(), NEW COW(), NEW FISH(), NEW FISH() GLY; EOL
PD PD VAR CLSS(Cow)[]PD VARI(herd) = SQU NEW COW(), NEW COW(), NEW COW() GLY; EOL
PD PD chatter(farm); EOL
PD PD chatter(ark); EOL
PD PD chatter(herd); EOL
PD END_MAIN EOL
END EOL
EOL
CLASS CLSS(Animal) EOL
BEGIN EOL
PD METHOD BOOLEAN FUNC(breathesUnderwater)() EOL
PD BEGIN EOL
PD PD RETURN FALSE; EOL
PD END EOL
EOL
PD METHOD BOOLEAN FUNC(isPredator)() EOL
PD BEGIN EOL
PD PD RETURN FALSE; EOL
PD END EOL
EOL
PD METHOD VOID FUNC(talk)() EOL
PD BEGIN EOL
PD END EOL
END EOL
EOL
CLASS CLSS(Dog) EXTENDS CLSS(Animal) EOL
BEGIN EOL
PD METHOD BOOLEAN FUNC(isPredator)() EOL
PD BEGIN EOL
PD PD RETURN TRUE; EOL
PD END EOL
EOL
PD METHOD VOID FUNC(talk)() EOL
PD BEGIN EOL
PD PD SYSTEM_OUT_PRINTLN(STRI("Woof woof!")); EOL
PD END EOL
END EOL
m4_end_indent
)
m5_question(BO(Question 17.2:) Write the following classes that
subclass the CLSS(Animal) class above: CLSS(Cow), CLSS(Cat), CLSS(Fish), and
CLSS(Whale).)
m5_question(BO(Question 17.3:) Write the CLSS(Shark) class which
extends CLSS(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 STRI(TT("Chomp Chomp!")).)
m5_question(BO(Question 17.4:) Run the CLSS(AnimalTest) class to
make sure that all the methods work correctly.)
m5_question(BO(Question 17.5:) Rewrite the TT(chatter) method so
that it never calls the TT(talk) methods and instead uses a series of
EM(if) statements and the EM(instanceof) operator to test the run-time
type of each object in the TT(a) array. Here is some code to get you
started:
m4_begin_indent
NU()PRIVATE FUNCTION VOID FUNC(chatter)(CLSS(Animal)[] VARI(a)) EOL
BEGIN EOL
PD FUR (VAR INT VARI(i)=NUMB(0); LT(i,a.length); i=i+NUMB(1)) EOL
PD BEGIN EOL
PD PD IF (a[i] INSTANCEOF CLSS(Cow)) THEN EOL
PD PD BEGIN EOL
PD PD PD SYSTEM_OUT_PRINTLN(STRI("Moo!")); EOL
PD PD END EOL
PD PD ELSE IF (a[i] INSTANCEOF CLSS(Cat)) THEN EOL
PD PD BEGIN EOL
PD PD PD SYSTEM_OUT_PRINTLN(STRI("Meow!")); EOL
PD PD END EOL
PD PD COMM(/* other code goes here */) EOL
PD END EOL
END EOL
m4_end_indent
NU()Note that the subclasses must appear before superclasses in the
above code, otherwise the wrong message will be printed out for
subclasses.)
m5_question(BO(Question 17.6:) Why is the code from the last
question not as good as calling each animal's TT(talk) method?)