2

I have an ArrayList of animals on land. All animals are of different classes, that extend an abstract superclass called Animal. They all have methods such as eat, walk, sleep, etc., but only the Bird class has the method fly.

How can I call the fly method on all Bird objects in the ArrayList?

public class Land{
    ArrayList<Animal> landAnimals = new ArrayList<Animal>();

    Land(Bird bird, Bird bird2, Bird bird3, Cat cat, Mouse mouse, Dog dog, Dog dog2){
        landAnimals.add(bird); 
        landAnimals.add(cat); 
        landAnimals.add(mouse);
        landAnimals.add(bird2); 
        landAnimals.add(dog); 
        landAnimals.add(bird3);
        landAnimals.add(dog2);
    } 

    public void animalsWalk(){ 
        int size=landAnimals.size(); 
        for (int count=0; count<size; count++){ 
            landAnimals.walk(); 
        } 
    }  

    public void birdsFly(){ 
        //How do I make birds in the arraylist fly?
    }
}
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48
Macmanmatty
  • 23
  • 1
  • 6

1 Answers1

1

First, you need to iterate over the contents of landAnimals. You can do that with a standard for loop:

for(int i = 0; i < landAnimals.size(); i++) {
    Animal animal = landAnimals.get(i);
    // TODO
}

Then you need to determine whether each particular animal object is of the Bird class. You can do that with the instanceof operator.

for(int i = 0; i < landAnimals.size(); i++) {
    Animal animal = landAnimals.get(i);
    if(animal instanceof Bird) {
        // TODO
    }
}

Then you need to cast animal to the Bird type, before you can call its fly method. Once you have done that, you can make the standard method call.

for(int i = 0; i < landAnimals.size(); i++) {
    Animal animal = landAnimals.get(i);
    if(animal instanceof Bird) {
        ((Bird) animal).fly();
    }
}
MultiplyByZer0
  • 6,302
  • 3
  • 32
  • 48