Java – ArrayList containing different objects of the same superclass – Methods for accessing subclasses

Hi, I want to know if there is a simple solution to my problem,

I have an ArrayList:

ArrayList <Animal> animalList = new ArrayList<Animal>(); 

/* I add some objects from subclasses of Animal */

animalList.add(new Reptile());
animalList.add(new Bird());
animalList.add(new Amphibian());

They all implement a method move () – when move () is called, bird can fly I know I can use it to access common methods and properties of superclasses

public void Feed(Integer animalIndex) {
    Animal aAnimal = (Animal) this.animalList.get(animalIndex);
    aAnimal.eat();
}

That's okay – but now I want to access the move () method of the subclass bird I can do this by projecting animals like birds:

Bird aBird = (Bird) this.animalList.get(animalIndex);
aBird.move();

In my case, I don't want to do this because it means that I have three different code sets above, each subtype is animal

It seems a little redundant. Is there a better way?

Solution

There is really no good way to do this from superclasses, because the behavior of each subclass will be different

To ensure that you actually call the appropriate mobile method, change animal from a superclass to an interface Then, when you call the move method, you will be able to ensure that the appropriate move method is called for the desired object

If you want to keep public fields, you can define an abstract class animalbase and require all animals to build it, but each implementation needs to implement the animal interface

Example:

public abstract class AnimalBase {
    private String name;
    private int age;
    private boolean gender;

    // getters and setters for the above are good to have here
}

public interface Animal {
    public void move();
    public void eat();
    public void sleep();
}

// The below won't compile because the contract for the interface changed.
// You'll have to implement eat and sleep for each object.

public class Reptiles extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Slither!");
    }
}

public class Birds extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Flap flap!");
    }
}

public class Amphibians extends AnimalBase implements Animal {
    public void move() {
        System.out.println("Some sort of moving sound...");
    }
}

// in some method,you'll be calling the below

List<Animal> animalList = new ArrayList<>();

animalList.add(new Reptiles());
animalList.add(new Amphibians());
animalList.add(new Birds());

// call your method without fear of it being generic

for(Animal a : animalList) {
    a.move();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>