有人能向我解释一下为什么Java不允许这样做吗?我有这三个文件(简化和简化为StackExchange):
一个超类,在我的例子中泛型图。类型参数指示弧的表示方式:要么使用特定的Arc类,要么用整数表示唯一的ID。
public interface Base<A> {
public boolean removeArc(A arc);
}一个子类,具有特定的弧形实现。
public interface Sub<B> extends Base<Arc<B>> {
@Override
public boolean removeArc(Arc<B> arc);
public Arc<B> removeArc(B value); //Removes an arc with this specific value.
}弧的实现。
public interface Arc<B> {
}Netbeans在Sub中给出了以下编译时错误。At @Override:
name clash: removeArc(Arc<B>) in Sub overrides a method whose erasure is the same as another method, yet neither overrides the other
first method: removeArc(B) in Sub
second method: removeArc(A) in Base
where B,A are type-variables:
B extends Object declared in interface Sub
A extends Object declared in interface Base在第二种方法中:
name clash: removeArc(B) in Sub and removeArc(A) in Base have the same erasure, yet neither overrides the other
where B,A are type-variables:
B extends Object declared in interface Sub
A extends Object declared in interface Base问题似乎是removeArc(Arc<B>)和removeArc(B)有相同的擦除,但我不明白为什么会发生这种情况。删除removeArc(Arc<B>)编译得很好,无需对@Override发出警告,因此它必须认识到Arc<B>等于Base中的A。
为什么在这种情况下,Java无法区分Arc<B>和B?
发布于 2014-02-03 01:45:10
编译器在编译时删除泛型类。它将取代位置持有人的限制等级。
在这种情况下,Base将用Object替换A的任何实例,而Sub将用Object替换B的任何实例。
这给出了相互矛盾的方法。
在基础public boolean removeArc(Object arc);中
在子public Arc removeArc(Object value);中
如果你做了
public interface Base<A extends Arc<?>> {
public boolean removeArc(A arc);
}然后将A的实例替换为Arc,并且方法签名不再冲突。
https://stackoverflow.com/questions/21518482
复制相似问题