仅指定某些类型参数对泛型派生类的引用会导致编译器出错"incompatible types"



为什么编译器报告以下代码的错误?

class B<T, U> {
T t; U u;
public B(T t, U u) { this.t = t; this.u = u; }
public T getT() { return t; }
public U getU() { return u; }
}
class D<T> extends B<T, String> {
public D(T t, String u) {
super(t, u);
}
}
public static void main(String[] args) {
D<Integer> d1 = new D<Integer>(1, "1");
String s1 = d1.getU();  // This line compiles
D d2 = new D<Integer>(1, "1");
String s2 = d2.getU();  // This line makes the compiler complain that getU returns Object and s2 is String
}

为什么最后一行不起作用?如果 getT() 不起作用,我会理解,因为该类型参数未在 s2 的类型中指定。但是getU总是会返回一个字符串...

使用泛型时,方法参数、返回类型和泛型类型都是从引用的编译时类型的方法调用中解析或推断出来的。

当你有

D<Integer> d1 = new D<Integer>(1, "1");
String s1 = d1.getU();  // This line compiles

编译器知道d1的类型为D<Integer>。它还将返回类型的d1.getU()解析为从其超类型String

但是,当使用原始类型时

原始类型的超类(分别称为超接口)是 擦除其任何超类(超接口) 参数化调用。

所以getU()显示为

public Object getU()

使用原始类型D的引用时。

最新更新