【发布时间】:2011-09-16 06:00:56
【问题描述】:
假设你有:
public interface A {}
public class B implements A {}
public class C {
void foo (List<A>) {}
}
public class Test {
//Declaration one
List<A> x = new List<A>();
//Declaration two
List<A> x = new List<B>();
B b = new B();
x.add(b);
new C().foo(x);
}
现在显然声明一是执行此操作的正确方法,但声明二会出现编译错误。我想知道为什么 Java 选择以这种特定方式强制执行类型安全;如果 Cats 列表仍然是 Animals 列表,为什么期望动物列表的方法拒绝接收一堆猫?
好奇心,比什么都重要 - 并且有机会更好地完善我的知识。
干杯, 戴夫。
【问题讨论】:
-
附带说明,我知道我们可以将 C 中的方法更改为以下内容: void foo(List extends A>) {} 但我仍然想知道为什么这种替换不无论如何都不会“自动”发生:)
标签: java generics inheritance collections