繁体   English   中英

带有接口的 Java 泛型限制

[英]Java generics restrictions with interfaces

抽象类

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

我尝试使用接口“危险”和“无害”来限制“动物园”类的方法。

用代码

public static <T extends Animal & Harmless > void tagHarmless(Animal Animal)。

Tiger 没有这个接口,所以它实际上不应该工作,是吗? 但是老虎也可以加入这个方法tagHarmless。

我没有看到错误。

感谢帮助。

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

它应该是:

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

至于您的main方法,您将PandaTiger实例分配给Animal变量。 因此,按照我的建议更改tagHarmless意味着pandatiger变量都不能传递给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); 将不会。

暂无
暂无

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

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