gpt4 book ai didi

java - 包含同一父类(super class)的不同对象的 ArrayList - 如何访问子类的方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:53:11 26 4
gpt4 key购买 nike

您好,我想知道是否有解决我的问题的简单方法,

我有一个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());

它们都实现了一个方法 move() - 当调用 move()Bird 会飞。我知道我可以使用这个访问父类(super class)的通用方法和属性

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

没关系 - 但现在我想访问 Bird 子类具有的 move() 方法。我可以通过将 Animal 转换为 Bird 来做到这一点:

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

在我的情况下,我不想这样做,因为这意味着我有 3 组不同的上述代码,每组对应 Animal 的每个子类型。

好像有点多余,有没有更好的办法?

最佳答案

There really isn't a nice way to do this from the superclass, since the behavior of each subclass will be different.

To ensure that you're actually calling the appropriate move method, change Animal from a superclass to an interface. Then when you call the move method, you'll be able to ensure that you're calling the appropriate move method for the object you want.

If you're looking to preserve common fields, then you can define an abstract class AnimalBase, and require all animals to build off of that, but each implementation will need 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();
}

关于java - 包含同一父类(super class)的不同对象的 ArrayList - 如何访问子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15995540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com