繁体   English   中英

如何使用 generics 使用类型有界参数接口

[英]How to use a type bounded parameter interface using generics

我有 class 测试,它有一个类型为 T 的实例变量 animalWithProps(这个变量应该是实现 AnimalProperty 的类型)。 但是,当我使用实现此接口(Dog)的 class 尝试此操作时,我收到无效类型的错误: Dog cannot be converted to T

interface AnimalProperty {
    String sound();
}

class Dog implements AnimalProperty {
    public String sound() {
        return "bark";
    }
}

class Test<T extends AnimalProperty> {
    T animalWithProp;

    public Test() {
        this.animalWithProp = new Dog();
        System.out.println(animalWithProp.sound());
    }
}

当我尝试做AnimalProperty prop = new Dog()时,它起作用了。 为什么我不能有这种类型的有界参数?

在您的示例中, T是 inheritance 树中Dog兄弟姐妹 例如,它可能是Cat Cat c = new Dog()有意义吗? 当然不会。 这就是你想要的:

class Test {
    AnimalProperty animalWithProp;

    public Test() {
        this.animalWithProp = new Dog();
        System.out.println(animalWithProp.sound());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM