KalebB KalebB - 8 days ago 6
Java Question

How can I pass a subclass as an argument for a method that wants the super class?

I want to be able to pass a Parrot (or any other animal) object into the method addAnimal(Animal animal). I know I could add animals to the array list directly from the constructor, but there will be other animals added later that will not be in the constructor. Hence, the public method.

How can I allow all kinds of animals to be passed as arguments?

**Edited to fix constructor and basic syntax issues. The problem still exists.

class Zoo extends Animal{
private ArrayList<Animal> animals;

public Zoo {
Parrot parrot = new Parrot();
animals.addAnimal(parrot); // cannot find methodaddAnimal(parrot)
}

public void addAnimal(Animal animal) {
animals.add(animal);
}
}

class Animal {
// variables and methods
}

class Parrot extends Animal {
// variables and methods
}

Answer

You are trying to invoke ArrayList object's addAnimal() method which DOES NOT exist, rather you need to invoke addAnimal() of the Zoo class object as shown in the below code with comments:

class Zoo {

    private ArrayList<Animal> animals;

    //create a main method
    public static void main(String[] args) {

       Zoo zoo = new Zoo();//Create Zoo object
       Parrot parrot = new Parrot();
       zoo.addAnimal(parrot);//add parraot to list by calling addAnimal
    }

   public void addAnimal(Animal animal) {
     animals.add(animal);
   }
}
Comments