java - 如何调用列表中某些对象实现的特定接口(interface)? java

标签 java list generics interface instanceof

假设我有一个基本的动物类

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/

相关文章:

java - 当父类(super class)没有构造函数时,如何在子类中声明构造函数

java - 如何从 servlet 中的项目文件夹提供输入文件

java - 按 LocalDate 降序和 LocalTime 升序对列表进行排序

java - Java 1.8.0_65 的推断类型问题

c++ - Rust 中泛型的单独编译

java - Android Junit 测试卡在 "Launching: Creating source locator..."

java - 在一种方法中设置变量的值并在另一种方法中打印

C++ 删除列表中的元音 <string>

python - 如何将大列表拆分成行?

C# - 我们应该如何在接口(interface)中实现 default(T)?