Jump to content


Chapter 8 Example Code

  • Please log in to reply
1 reply to this topic

#1 wfc7


    New Member

  • Members
  • Pip
  • 1 posts

Posted 22 August 2014 - 02:25 PM


The topic of polymorphism has been a bit challenging, and although I just finished the chapter, exercises and all, I'm still a bit confused about the "AnimalTestDrive" example shown on page 207. Is that supposed to be a complete code? I tried to compile it unsuccessfully. Thanks in advance!

public class MyAnimalList {

private Animal[] animals = new Animal[5];
private int nextIndex = 0;

public void add ( Animal d) {

animals[nextIndex] = d;
if (nextIndex < animals.length) {
System.out.println("Animal added at " + nextIndex);


public class AnimalTestDrive implements Animal {
public static void main(String[] args) {

MyAnimalList list = new MyAnimalList();
Dog a = new dog();
Cat b = new cat();

#2 always_java


    New Member

  • Members
  • Pip
  • 1 posts

Posted 02 November 2014 - 07:49 AM

The program given is perfect logically but however incomplete.
Inorder to have the full program follow the directions mentioned below:

1. make a dog class first. (dog.java) (you can choose to name each of them as dog.java,cat.java,(animal.java which is super class).
2. make a cat class .(cat.java)
3. inherit these above mentioned classes to an animal class.(animal.java)
4.Now create one more class as myanimallist and write the first block of code of page 207 on it save as seperate file.(myainimalist.java)
5. finally, make a class called animal test drive which has the main function mentioned at the second block on page 207.(animaltestdrive.java)
Run the project.
Be careful with the references and classes you use in all these files . This will definitely solve your problem...GOOD LUCK

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users