简体   繁体   中英

Adding items to an array that is a member variable in another class?

My assignment is to add animals that I have created to an enclosure. Animal is an abstract class used to create 4 animals one of which is "croc". Unfortunately I receive an error message when I try to add items to an enclosure.

public class Main {

   public static void main(String[] args) {

   //animals and enclosures created sucessfully here.

   firstEnclosure.addAnimal(croc);

}
public class Enclosure {
    private Animal[] animals;

    public void setAnimal(Animal[] animal){
        this.animals = animal;
    }

    public void addAnimal(Animal animal) {
       setAnimal(animal);

}

The error message reads:

error: incompatible types: Animal cannot be converted to Animal[] setAnimal(animal);

Below is the issue:

public class Enclosure {
    private Animal[] animals;

    public void setAnimal(Animal[] animal){
        this.animals = animal;
    }

    public void addAnimal(Animal animal) {
       setAnimal(animal); // <--**Setting Animal object to the Animal array Object**
}
``````

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM