问题
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?
回答1:
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?
回答2:
interface CollectionConverter<U> {
<T> List<T> toList(Collection<T> c);
void fooMethod(Class<?> c);
<E>Comparable<E> method3(E e);
Comparable<U> method4(U u);
}
class Overrider implements CollectionConverter<Integer> {
@Override
public List toList(Collection c) {
return null;
}
@Override
public void fooMethod(Class c) {
}
@Override
public Comparable method3(Object o) {
return null;
}
@Override
public Comparable method4(Integer u) {
return null;
}
}
This code works well. In JLS: The notion of subsignature is designed to express a relationship between two methods whose signatures are not identical, but in which one may override the other. Specifically, it allows a method whose signature does not use generic types to override any generified version of that method. This is important so that library designers may freely generify methods independently of clients that define subclasses or subinterfaces of the library.
回答3:
Did you try using Integer instead of Object obj i.e
public boolean add(Integer i)
{ //compiler error
return true;
}
The problem is that when you are extending Hashset , you are extending Integer Hashset and not the generic form. So, in the subclass your add method has to comply with the signature of the superclass method which is
public boolean add(Integer i) { }
If you want to extend from a totally generic Hashset implementation, try extending with
public class MyHashset extends Hashset<?> {
}
Then your add method should work with Object.
来源:https://stackoverflow.com/questions/8768028/name-clash-the-method-addobject-of-type-test2-has-the-same-erasure-as-adde