【发布时间】:2012-04-03 12:49:36
【问题描述】:
可能重复:
Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?
Java Generics — Assigning a list of subclass to a list of superclass
使用原始类型,您可以轻松说出这样的话。
[...] // MyClass is generic with upper bound of Object
MyClass c = new MyClass<Double>();
[...]
但这是不允许的
MyClass<Number> c = new MyClass<Double>()
我不明白这是为什么。我的书告诉我为什么第二个不起作用,因为您不能将整数添加到 MyClass<Double>。它没有解释为什么 MyClass<Double> 是 MyClass<Object> 的子类(或等效的原始类型形式),因为 double 是对象的子类。
那么,如果第二种形式不允许,为什么第一种允许。请意识到我是新手。
编辑:更进一步,如果 Number 是上限,在第一个示例中会发生什么?
你可以在这里看到类型擦除的效果
class Untitled {
public static void main(String[] args) {
}
public static<T> void c(T t)
{
t.SubClassMethod();// this won't work because class Object has no such method. But if I change the upperbound to SubClass it will.
t.toString() // this will because class Object has such a method
}
}
我的观点是,为什么声明 Generic 就像它最终被视为上限一样重要?
【问题讨论】:
-
我的问题是相反的,我在问为什么你可以从一个子类分配一个原始类型
-
该问题的前提也是错误的,因为类型擦除只关心上限是否与方法一起使用,并使用类型检查强制转换。至少这是我读过的内容