带有接口的java泛型限制

yb3bgrhw  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(275)

抽象类

public abstract class Animal {

private int id;
private String name;

public Animal(int id, String name) {
    this.id = id;
    this.name = name;
}}

_动物1的孩子

public class Tiger extends Animal implements Dangerous {

public Tiger(int id, String name) {
    super(id, name);
} }

_动物之子2

public class Panda extends Animal implements Harmless{

public Panda(int id, String name){
    super(id, name);
}}

_双属性接口

public interface Dangerous {}
public interface Harmless {}
public class Zoo {

public static <T extends Animal & Harmless> void tagHarmless(Animal animal) {
    System.out.println("this animal is harmless");
}

public static <T extends Animal & Dangerous> void tagDangerous(Animal animal) {
    System.out.println("this animal is dangerous");
}}
public class App {
public static void main(String[] args) {

    Animal panda = new Panda(8, "Barney");
    Animal tiger = new Tiger(12, "Roger");

    Zoo.tagHarmless(panda);
    Zoo.tagHarmless(tiger);

}}

-结果

this animal is harmless
this animal is harmless

Process finished with exit code 0

我试图用接口“危险”和“无害”来限制类“zoo”的方法。
使用代码
公共静态<t扩展动物&无害>无效标记无害(动物)。
tiger没有这个接口,所以它实际上不应该工作,是吗?但是老虎也可以加入到这个方法中。
我看不出有错。
谢谢你的帮助。

vkc1a9a2

vkc1a9a21#

您正在声明泛型类型参数 T ,但您的方法从未使用过它。您的方法接受 Animal 参数,这意味着任何 Animal 这是可以接受的。
应该是:

public static <T extends Animal & Harmless> void tagHarmless(T animal) {
    System.out.println("this animal is harmless");
}

至于你的 main 方法,则指定 PandaTiger 示例 Animal 变量。因此,改变 tagHarmless 正如我所建议的,这意味着 panda 也不是 tiger 变量可以传递给 tagHarmless (自 Animal 不执行 Harmless ).
如果你改变主意 main 致:

Panda panda = new Panda(8, "Barney");
Tiger  tiger = new Tiger(12, "Roger");

Zoo.tagHarmless(panda);
Zoo.tagHarmless(tiger);

呼吁 Zoo.tagHarmless(panda); 将通过编译,并调用 Zoo.tagHarmless(tiger); 不会。

相关问题