错误覆盖Java中的泛型集合 [英] error in overriding generic collections in Java

查看:190
本文介绍了错误覆盖Java中的泛型集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试重写一个采用 List< String> 的方法时,出现以下编译错误。 b
$ b


此行的多个标记:

- 方法 getname(List child 的$ c>必须覆盖或实现一个超类型方法

- 名称冲突:方法 getname(List< Integer> ; > > 与 getname(List< String>)的类型父母但不覆盖它


这是由于擦除,一种采用 List< String> 的方法,以及一个采用 List< Integer>的子类方法; 会被视为被重写,因为擦除后两种方法的签名都是相同的。

这里是涉及擦除的方法签名的定义。

我不明白为什么会这样

我的代码如下:

  class parent {

public void getname(List< String> num){
System.out.printf(parent class:%s,num);
}

}

class child extends parent {

@Override //这里是编译错误
public void getname(List< Integer> num){
System.out.printf(child class:%s,num);
}
}


解决方案

错误消息非常清晰:它具有相同的擦除,但类型不匹配,因此它不被视为覆盖。 A List< Integer> 不是 List< String> ;它不能将其视为覆盖(这将要求类型完全匹配),也不能将其视为重载(这将要求擦除有所不同)。


When I try to override a method that takes a List<String>, I get the following compile error.

Multiple markers at this line:
- The method getname(List<Integer>) of type child must override or implement a supertype method
- Name clash: The method getname(List<Integer>) of type child has the same erasure as getname(List<String>) of type parent but does not override it

I was under the impression, that due to erasure, a method that takes a List<String> and a subclass method that takes a List<Integer> would be considered as overridden, because the signature of both methods are same after erasure.

Here is the definition for method signature that involves erasure.
I do not understand why this error comes and what exactly it means.

My code is below:

class parent {

     public void getname(List<String> num) {
        System.out.printf("parent class: %s",num);
     }

}

class child extends parent {

    @Override  // here is the compile error
    public void getname(List<Integer> num) {
        System.out.printf("child class: %s",num);
    }
}

解决方案

The error message is pretty clear: it has the same erasure, but the types don't match, so it's not considered an override. A List<Integer> is not a List<String>; it can't treat it as either an override (which would require the types to match exactly) nor an overload (which would require the erasures to be different).

这篇关于错误覆盖Java中的泛型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆