Exercise 2: Working With Interfaces and Abstract Classes (Level 1)

In this exercise, you will  create abstract classes and interfaces, and explore the polymorphic properties of these types of components. You will create a hierarchy of animals that is rooted in an abstract class Animal. Several of the animal classes will implement an interface called Pet. Figure 7-2 shows a UML class diagram of the animal classes that you will create.





Preparation

Before you begin, make sure that you have changed directories to exercises/mod07_class2/exercise2/ using the cd command in the terminal window.

cd ~exercises/mod07_class2/exercise2/

Task 1 - Creating the Animal Classes and Pet Interface

Create a source file for each class and interface shown in Figure 7-2 on page Lab 7-9. Make the action methods (walk, eat and play) print a statement to standard output that reflects the animal. For example, the walk method for the Animal class might say something similar to This animal walks on 4 legs, where 4 is the value of the legs attribute.

Task 2 - Creating the TestAnimals Program

Create a TestAnimals program. Have the main method create and manipulate instances of the classes you created above.

Start with:

Fish d = new Fish();
Cat c = new Cat("Fluffy");
Animal a = new Fish();
Animal e = new Spider();
Pet p = new Cat();

Experiment by:

Task 3 - Compiling the TestAnimals Program

On the command line, use the javac command to compile the test program.

Task 4 - Running the Testanimals Program

On the command line, use the java command to run the test program.