java - 引用泛型派生类仅指定一些类型参数会导致编译器出现 "incompatible types"错误

标签 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(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/

相关文章:

java - 获取数组中选中的复选框数据

java - 在java中调用log4j记录器 "Generic Class"

Java-有关泛型的错误

c# - IEnumerable 跳过并获取

java - 在 JPQL 中迭代集合

java - 在 java 中如何有效地从文件中读取 x 行,关闭它,然后再次打开它,从第 x 行开始并继续阅读

c# - 检查类型是否为 Nullable 的正确方法

generics - Rust:定义比较长度的通用函数的特征

Java 语言检测在给定相同输入的情况下返回不同的概率

java - 露天共享认证