名称冲突:类型为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
问题描述
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
- When does a method override its supertype's method?
- Can a method of a non-generic subtype override a method of a generic supertype?
这篇关于名称冲突:类型为test2的方法add(Object)与类型HashSet< E>的add(E)具有相同的擦除。但不会覆盖它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!