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.
Angelika Langer Generics FAQ
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With