Java 引用泛型派生类仅指定某些类型参数会导致;“不兼容类型”;来自编译器的错误
为什么编译器会报告以下代码的错误Java 引用泛型派生类仅指定某些类型参数会导致;“不兼容类型”;来自编译器的错误,java,generics,Java,Generics,为什么编译器会报告以下代码的错误 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(
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
}
B类{
T;U;
公共B(T,U){this.T=T;this.U=U;}
公共T getT(){return T;}
公共U getU(){return U;}
}
D类扩展了B类{
公共D(T,字符串u){
超级(t,u);
}
}
公共静态void main(字符串[]args){
D d1=新的D(1,“1”);
字符串s1=d1.getU();//此行编译
D d2=新的D(1,“1”);
String s2=d2.getU();//这一行使编译器抱怨getU返回Object,而s2是String
}
为什么最后一行不行?如果getT()不起作用,我会理解,因为s2的类型中没有指定该类型参数。但是,当使用泛型时,getU将始终返回字符串…,方法参数、返回类型和泛型类型都是从引用的编译时类型的方法调用中解析或推断出来的 当你有
D<Integer> d1 = new D<Integer>(1, "1");
String s1 = d1.getU(); // This line compiles
使用原始类型的引用时,请阅读原始类型。
public Object getU()