为什么下面的代码编译器会报错?
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
来自它的父类(super class)型。
但是,当使用 raw types 时
The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations.
所以 getU()
显示为
public Object getU()
使用原始类型的引用时 D
.
关于java - 引用泛型派生类仅指定一些类型参数会导致编译器出现 "incompatible types"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237405/