假设我有一个基本的动物类
abstract class Animal {
// basic animal code
}
现在我有 2 种不同的动物...
public class Dog extends Animal{
// dog code
}
和
public class Bird extends Animal implements Flyable{
// bird code
@Override
public void fly() {
System.out.println("flap flap");
}
}
Flyable 是一个简单的接口(interface),只有一个方法:
public void fly();
如果我有一个动物列表,我想遍历它,告诉鸟儿飞但让狗独自一人,我该如何实现?
public class Test {
public static List<Animal> animals = new ArrayList<Animal>();
public static void main(String[] args) {
animals.add(new Bird("flop"));
animals.add(new Dog("plop"));
for(Fly f : animals) { // exception here because of mismatch of types
f.flap();
}
}
}
到目前为止,我发现的唯一选择是使用 instanceof 来确定一个类是否实现了 Flyable 接口(interface),但快速谷歌搜索表明这对业务不利。 来源例如: https://www.quora.com/Is-using-instanceof-in-Java-consider-bad-practice-Any-alternative-to-using-this-keyword 将 instanceof 的使用视为糟糕的设计。
我觉得有一种我以前见过的直观方法可以做到这一点,但找不到好的解决方案。
最佳答案
Flyable is a simple interface that holds a single method:
public void fly();
我想这是一个打字错误,因为您调用的方法名为 flap
而不是 fly
。
您可以通过使用 instanceof
关键字来检查类是否 is-a
父类(super class)来解决此问题。
for(Animal animal : animals) { // loop through all animals
if(animal instanceof Flyable) { // if that animal IS-A Flyable (so it can fly)
((Flyable) animal).flap(); // cast to Flyable and let it fly!
}
}
The only option I have found so far is using instanceof to determine whether a class implements the Flyable interface, but a quick google search suggests this is bad for business
我觉得还不错。这是完成任务的唯一方法。
关于java - 如何调用列表中某些对象实现的特定接口(interface)? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084781/