开发者

Can I manually override inherited methods?

开发者 https://www.devze.com 2023-04-02 02:21 出处:网络
That\'s a very imperfect title... public class A extends AbstractList { public boolean addAll(int index, Collection<E> what){}

That's a very imperfect title...

public class A extends AbstractList
{
   public boolean addAll(int index, Collection<E> what){}
}

but Eclipse gives me the compile error

Name clash: The method addAll(int, Collection<E>) of type DynamicArray<E> has the same
erasure as addAll(int, Collection<? extends E>) of type AbstractList<E> but does not 
override it

I understand what the problem with the erasure is, but I don't understand why addAll(int, Collection<E>) doesn't override the inherited method it's having conflicts with (If both were defined in开发者_JS百科 the same class I could see it, but the problem is: "When a method has the same erasure as an inherited method, we override the inherited method. But this one has the same erasure, so it won't work").

Is there any way to force the compiler to overwrite AbstractList.addAll(int, Collection<? extends E>) with DynamicList.addAll(int, Collection<E>)?


Specifically, the original addAll(int, Collection<? extends E>) states that the second parm can be any collection of items that may extend E, while your version addAll(int, Collection<E>) requires that the items be E exactly, and they cannot extend E.


You need to give the exact same signature as the method to be overridden:

 public boolean addAll(int index, Collection<? extends E> what)

Is there any way to force the compiler to overwrite AbstractList.addAll(int, Collection<? extends E>) with DynamicList.addAll(int, Collection<E>)?

If you are thinking of overloading: No. The two methods could not be distinguished because of erasure. So there can be only one.

If you are thinking of overriding: Well, if you specify a different signature, that would not be overriding, would it? You could not narrow Collection to ArrayList in the signature, either, right?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号