Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 258
Ashish Sharma Avatar asked Jan 07 '12 07:01

Ashish Sharma


2 Answers

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?
like image 63
Mark Peters Avatar answered Sep 28 '22 13:09

Mark Peters


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.

like image 21
Yan Yan Avatar answered Sep 28 '22 11:09

Yan Yan