名称冲突:类型为test2的方法add(Object)与类型HashSet< E>的add(E)具有相同的擦除。但不会覆盖它 [英] Name clash: The method add(Object) of type test2 has the same erasure as add(E) of type HashSet<E> but does not override it

查看:123
本文介绍了名称冲突:类型为test2的方法add(Object)与类型HashSet< E>的add(E)具有相同的擦除。但不会覆盖它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util。*;

  class A extends HashSet< Integer> {
public boolean add(Object obj){//编译器错误
return true;
}
}

class Abc< T> {
public void add(T t){} //编译器错误
public void add(Object i){} //编译器错误(无法重载?)
}

错误:名称冲突:test2类型的add(Object)方法与add(E)键入HashSet但不覆盖它

我不知道上述错误背后的概念是什么,任何一个都可以提示我可以研究这个概念?

解决方案

这里的工作概念叫做 type erasure HashSet 定义了一个方法 add(T),并且定义了一个方法 add(Object) 。一眼就可以认为这是好的;你的方法只是重载 add 。但是, T 的删除是 Object ,因此两者具有相同的擦除签名。

现在,如果您的方法正确地覆盖 HashSet 中的方法,那就没有问题。但为此,您应该使用 add(Integer)而不是 add(Object)。你不能正确覆盖父方法,所以相反,它被报告为冲突,因为类不能提供两个方法具有相同的签名。



您的 Abc 示例遵循相同的推理。您声明的两种方法具有相同的擦除签名,因此它们发生冲突。

进一步阅读



Angelika Langer Generics常见问题


import java.util.*;

  class A extends HashSet<Integer> {
       public boolean add(Object obj){  //compiler error
        return true;
       }
    }
    or
   class Abc <T> {
    public void add(T t){}  //compiler error
    public void add(Object i){} //compiler error (can't overload?)
    }

Error:Name clash: The method add(Object) of type test2 has the same erasure as add(E) of type HashSet but does not override it

i do not know what is the concept behind above error can any one suggest where i can study this concept?

解决方案

The concept at work here is called type erasure. HashSet defines a method add(T), and you define a method add(Object). At a glance one might think this is OK; that your method just overloads add. However, the erasure of T is Object and so the two have the same erased signature.

Now, that would be fine if your method properly overrode the method from HashSet. But to do so you should be using add(Integer) and not add(Object). You're not properly overriding the parent method, so instead it is reported as a conflict since a class cannot provide two methods with the same signature.

Your Abc example follows the same reasoning. The two methods you declared have the same erased signature so they clash.

Further Reading

Angelika Langer Generics FAQ

这篇关于名称冲突:类型为test2的方法add(Object)与类型HashSet&lt; E&gt;的add(E)具有相同的擦除。但不会覆盖它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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