您好,我想知道是否有一个简单的解决方案可以解决我的问题,
我有一个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()
- The Bird
飞翔时move()
叫做。
我知道我可以使用这个来访问超类的常用方法和属性
public void feed(Integer animalIndex) {
Animal aAnimal = (Animal) this.animalList.get(animalIndex);
aAnimal.eat();
}
很好 - 但现在我想访问move()
子类方法Bird
有。
我可以通过投射来做到这一点Animal
as a Bird
:
Bird aBird = (Bird) this.animalList.get(animalIndex);
aBird.move();
在我的情况下,我不想这样做,因为这意味着我有 3 个不同的上述代码集,每个子类型都有一个Animal
.
好像有点多余,有更好的办法吗?
实际上没有一个好的方法可以从超类中执行此操作,因为每个子类的行为都会有所不同。
确保您确实拨打了适当的电话move
方法、改变Animal
从超类到接口。然后当你打电话时move
方法,您将能够确保为所需的对象调用适当的移动方法。
如果您想保留公共字段,那么您可以定义一个抽象类AnimalBase
,并要求所有动物以此为基础,但每次实施都需要实施Animal
界面。
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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)