【问题标题】:Java generics restrictions with interfaces带有接口的 Java 泛型限制
【发布时间】:2021-10-03 03:14:53
【问题描述】:

抽象类

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 & Harmless> void tagHarmless(Animal animal).

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

我没有看到错误。

感谢您的帮助。

【问题讨论】:

    标签: java generics


    【解决方案1】:

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

    应该是:

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

    至于您的main 方法,您将Panda 和Tiger 实例分配给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); 的调用则不会。

    【讨论】:

    • 然后我遇到了类应用程序“Zoo.tagHarmless(panda);”的问题。必需类型 T ,提供 Animal
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多