带有接口的 Java 泛型限制

Rid*_*ido 3 java generics

抽象类

public abstract class Animal {

private int id;
private String name;

public Animal(int id, String name) {
    this.id = id;
    this.name = name;
}}
Run Code Online (Sandbox Code Playgroud)

_动物 1 的孩子

public class Tiger extends Animal implements Dangerous {

public Tiger(int id, String name) {
    super(id, name);
} }
Run Code Online (Sandbox Code Playgroud)

_动物 2 的孩子

public class Panda extends Animal implements Harmless{

public Panda(int id, String name){
    super(id, name);
}}
Run Code Online (Sandbox Code Playgroud)

_ 两个属性接口

public interface Dangerous {}
public interface Harmless {}
Run Code Online (Sandbox Code Playgroud)
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");
}}
Run Code Online (Sandbox Code Playgroud)
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);

}}
Run Code Online (Sandbox Code Playgroud)

-结果

this animal is harmless
this animal is harmless

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

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

用代码

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

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

我没有看到错误。

感谢帮助。

Era*_*ran 8

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

它应该是:

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

至于您的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);
Run Code Online (Sandbox Code Playgroud)

调用Zoo.tagHarmless(panda);将通过编译,而调用Zoo.tagHarmless(tiger);则不会。