Next: , Previous: , Up: J.T.W. Tutorials [Contents][Index]


4.17 Tutorial 17 Arrays inheritance and polymorphism

Question 4.17.1: Study, compile and run the following code:

class AnimalTest
begin
  private function void chatter(Animal[] a)
  begin
    superfor (var int i=0 to a.length-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 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:

private function void chatter(Animal[] a)
begin
  superfor (var int i=0 to a.length-1)
  begin
    if (a[i] instanceof Cow) then
    begin
      System.out.println("Moo!");
    end
    elseif (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 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: , Previous: , Up: J.T.W. Tutorials [Contents][Index]

AltStyle によって変換されたページ (->オリジナル) /