我可以手动重写继承的方法吗?
这是一个非常不完美的标题...
public class A extends AbstractList
{
public boolean addAll(int index, Collection<E> what){}
}
但是 Eclipse 给了我编译错误
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
我明白擦除的问题是什么,但我不明白为什么 addAll(int, Collection
不这样做'不重写与之冲突的继承方法(如果两者都在同一个类中定义,我可以看到它,但问题是:“当一个方法与继承方法具有相同的擦除时,我们会重写继承方法。但是这个具有相同的擦除,因此不会起作用”)。
有没有办法强制编译器用 DynamicList.addAll(int, Collection
AbstractList.addAll(int, Collection)
?
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 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>)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
具体来说,原始的 addAll(int, Collection) 声明第二个参数可以是任何可能扩展 E 的项目集合,而您的版本 addAll(int, Collection) 则表明第二个参数可以是任何可能扩展 E 的项目集合。 E>) 要求这些项完全是 E,并且它们不能扩展 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 versionaddAll(int, Collection<E>)
requires that the items be E exactly, and they cannot extend E.您需要提供与要重写的方法完全相同的签名:
如果您正在考虑重载:否。这两种方法由于擦除而无法区分。所以只能有一个。
如果您正在考虑覆盖:那么,如果您指定不同的签名,那么就不会覆盖,不是吗?您也不能在签名中将 Collection 缩小为 ArrayList,对吧?
You need to give the exact same signature as the method to be overridden:
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?