0

I just started learning Java and have a very basic question. I came across this code in a book where the Animal-specific list is built, I read the first part of the code with the MyAnimalList class and thought that was it, but then saw the AnimalTestDrive class below.

Why do we need this Test class, to test our code? Does that mean if the MyAnimalList class is part of some wider code, we wouldn't include the AnimalTestDrive class in there?

Also, would these two classes have to be in different Java files?

public class MyAnimalList {

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

   public void add(animal a) {
      if (nextIndex < animals.length) {
         animals[nextIndex] = a;
         System.out.println("Animal added at " + nextIndex);
         nextIndex++; 

    }
  }
}


public class AnimalTestDrive {
 public static void main (String[] args) {
   MyAnimalList list = new MyAnimalList();
   Dog a = new Dog();
   Cat c = new Cat();
   list.add(a);
   list.add(c);

   }
 }
MilTom
  • 157
  • 1
  • 5
  • 3
    You need a main method as a starting point for your application. It can be in a "test" class or in your Animal class. The only purpose of this AnimalTestDrive class is to hold this main method, but that's an important purpose. – Hovercraft Full Of Eels Oct 10 '16 at 19:40
  • Those classes do have to be in separate files. You can't define two `public class`-es at the "same top-level" of a file – OneCricketeer Oct 10 '16 at 19:46
  • MyAnimalList is your definition of beahvior about animals: - What is the attributes (name, size) of an animal - What is done when add new animal AnimalTestDrive will call MyAnimalList class and play with it: - Instance new animals - Define your characteristics and actions – ℛɑƒæĿᴿᴹᴿ Oct 10 '16 at 19:48

0 Answers0