AnimalTest.java Questions

Instructions

  1. With the left mouse button pressed, drag the mouse across the contents of the program listing that is shown below. This will select the program listing. Then choose Copy from the Edit menu of your web browser to copy the program listing to the clipboard.
  2. Start your text editor and create a new file called AnimalTest.java. Choose Paste to paste the contents of the program listing from the clipboard into the new file.
  3. Save the file to disk and begin answering the questions that are shown below.
  4. When you need to look at the model answer, click here.
  5. Click here to go back to the tutorials menu.

Program listing

// ARRAYS, INHERITANCE AND POLYMORPHISM TUTORIAL
// Copyright (C) 1998-2016 Davin Pearson
// Website: http://davin.50webs.com/java-tutorials

class AnimalTest
{
   private static void chatter(Animal[] a)
   {
      for (int i=0; i<a.length; i++)
      {
         a[i].talk();
      }
   }

   /*
    *
    * The main method is the point of entry into the program...
    *
    */
   public static void main(String[] args)
   {
      Animal[] farm = { new Dog(), new Cow(), new Kiwi() };

      Animal[] ark = { new Dog(), new Dog(), new Cow(), new Cow(),
                       new Kiwi(), new Kiwi() };

      Cow[] herd    = { new Cow(), new Cow(), new Cow() };

      chatter(farm);

      chatter(ark);

      chatter(herd);
   }
}

class Animal
{
   public boolean hasWings()
   {
      return false;
   }

   public boolean canFly()
   {
      return false;
   }

   public void talk()
   {
   }
}

class Dog extends Animal
{
   public void talk()
   {
      System.out.println("Woof woof!");
   }
}

// QUESTIONS:
//
// (1) Write the class Cow which extends class Animal.  Override all
// necessary methods.
//
// HINT: Look at how class Dog inherits from class Animal and
// follow the pattern.
// 
// (2) Write the class Bird which extends class Animal.  Override all
// necessary methods.
//
// (3) Write the class Kiwi which extends class Bird.  Override all
// necessary methods.
// 
// (4) Run the AnimalTest class to make sure that all the methods
// work correctly.
//
// (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 array "a".
//