抽象类
public abstract class Animal {
private int id;
private String name;
public Animal(int id, String name) {
this.id = id;
this.name = name;
}}
_动物 1 的 child
public class Tiger extends Animal implements Dangerous {
public Tiger(int id, String name) {
super(id, name);
} }
_动物 2 的 child
public class Panda extends Animal implements Harmless{
public Panda(int id, String name){
super(id, name);
}}
_ 两个属性接口(interface)
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
我尝试使用“危险”和“无害”接口(interface)来限制“动物园”类的方法。
用代码
public static
Tiger 没有这个接口(interface),所以它实际上不应该工作,是吗? 但是老虎也可以在这个方法中加入tagHarmless。
我没有看到错误。
感谢您的帮助。
最佳答案
您正在声明一个泛型类型参数 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);
的调用不会。
关于Java 泛型对接口(interface)的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68542448/