Page 1 of 1
About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Fri Sep 20, 2013 4:46 pm
by javatek202
What is the best way to fix this compile error, which says
name clash: add(Object) in BookList and add(E) in ArrayList have the same erasure, yet neither overrides the other
?
Can you explain the error and how it would be fixed.
Re: About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Fri Sep 20, 2013 5:32 pm
by admin
Re: About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Sat Feb 11, 2023 3:09 am
by asi-aal
Why method add(E e) can not be overloaded?
Following code won't compile
public boolean add(Object o)
{
if(o instanceof Book ) return super.add((Book) o);
else return count++ == -1;
}
public boolean add(Book o)
{
if(o instanceof Book ) return super.add((Book) o);
else return count++ == -1;
}
Re: About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Sun Feb 12, 2023 11:48 am
by admin
Please post complete code that you tried to compile along with the error message.
Re: About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Wed Dec 20, 2023 3:01 pm
by JavaMara
The link is no longer available, can you add the fix here please ?
Re: About Question com.enthuware.ets.scjp.v6.2.95 :
Posted: Wed Dec 20, 2023 10:39 pm
by admin
ArrayList has an add(Object ) method. But in the given code, we are using ArrayList<Book>, which means that ArrayList has been parameterized to use Book and so, from the compiler's perspective, ArrayList<Book> now has as add(Book ) method (instead of add(Object ) ).
Next, we have defined BookList to extend from ArrayList<Book>, this means that if we want to override the add(Book ) method in the BookList class, we need to define it as add(Book ). If we define it as add(Object ), the compiler will consider it an overload (because base class has add(Book ) and subclass has add(Object ) ). However, this overload will not work for the JVM because generics are not reified. The JVM doesn't see the generic information and so it doesn't know that anything like ArrayList<Book> exists. It only knows about ArrayList.
So, now you can see that there is a contradiction - from compiler's perspective it is a overload but from the JVM's perspective it is an override. To avoid this contradiction, the compiler doesn't allow it.
If you are not sure about reification in generics, you will need to go through a good book to read about it first.