任何人都可以解释为什么 Cage 对象能够接受任何对象类型,即使在创建 Cage 对象时定义了泛型方式只接受 Monkey 类型对象。下面是参考代码。正如您在下面的代码引用 newMonkeyCage1 和 newMonkeyCage2 中看到的那样,没有错误,为什么???感谢所有帮助。谢谢
public class Zoo {
public static void main(String[] args) {
Cage<Monkey> monkeyCage = new Cage<Monkey>(new Monkey(), new Lion()); //CE : coz of Constructor, all E is converted to Monkey
Cage<Monkey> newMonkeyCage1 = new Cage(new Monkey(), new Lion()); // No Error, why???? accepts Lion Type
Cage<Monkey> newMonkeyCage2 = new Cage(new Monkey(), new String()); // No Error, why??? accepts even String() type.
Cage<Monkey> newMonkeyCage = new Cage<Monkey>(new Monkey(), new Monkey()); // No Error, works as expected.
Cage<Monkey> newMonkeyCage = new Cage<Monkey>(new Monkey(), new Lion()); // CE : works as expected.... Required type:Monkey Provided:Lion
}
}
class Cage<E> {
private E animal1;
private E animal2;
public Cage() {
}
public Cage(E animal1, E animal2) {
this.animal1 = animal1;
this.animal2 = animal2;
}
public E getAnimal1() {
return animal1;
}
public void setAnimal1(E animal1) {
this.animal1 = animal1;
}
public E getAnimal2() {
return animal2;
}
public void setAnimal2(E animal2) {
this.animal2 = animal2;
}
}
如果 Java 中没有提供泛型(例如: new Cage(new Monkey(), new Lion()); ),代码可以编译,但不是类型安全的。这意味着编译器将无法捕获某些类型的错误,这可能会导致运行时出现错误。
Cage<Monkey> newMonkeyCage1 = new Cage(new Monkey(), new Lion());
Cage<Monkey> newMonkeyCage2 = new Cage(new Monkey(), new String());
这里你没有给出 作为通用参数,因此 java 不会严格检查你的类构造函数。