以下代码

public interface IGiveUp
{
    void surrender(List<Class> l);
}
public class GiveUp implements IGiveUp {

    @Override public void surrender(List<Class> l) {}
}

编译正常。但是当我向接口(interface)添加一个未使用的泛型类型参数时
public interface IGiveUp<X>
{
    void surrender(List<Class> l);
}

编译失败 (javac 1.6.0_23)
IGiveUp.GiveUp is not abstract and does not override abstract method surrender(java.util.List)

如果我在实现中指定泛型,它将编译
public class GiveUp implements IGiveUp<Object>

或使方法参数成为非泛型类型的列表
void surrender(List l);

最佳答案

您的类正在尝试实现 raw type IGiveUp - 该原始类型对泛型一无所知,因此 type erasure 之后的方法签名就是:

void surrender(List l)

方法参数没有使用接口(interface)声明中的类型参数并不重要:类型擦除会从签名中删除泛型的所有痕迹。

基本上,您应该尽可能避免原始类型。有关更多详细信息,请按照上面的链接转到 JLS 的部分,或阅读 Java Generics FAQ

关于java - 向接口(interface)添加未使用的泛型参数如何阻止类实现它?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18277713/

10-09 06:54
查看更多