[英]Type erasure prevents overloading, but allows overriding
誰能向我解釋為什么Java不允許這樣做? 我有以下三個文件(為StackExchange剝離並簡化):
對於我的通用圖,是超類。 類型參數指示弧的表示方式:具有特定的弧類別,或者具有指示唯一ID的整數。
public interface Base<A> {
public boolean removeArc(A arc);
}
一個子類,具有針對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中為我提供了以下編譯時錯誤。 在@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>
等於A
在Base
。
在這種情況下,為什么Java無法區分Arc<B>
和B
?
編譯器在編譯時刪除泛型類。 它將使用受限類替換占位符。
在這種情況下Base
將取代的任何實例A
與Object
和Sub
將取代的任何實例B
與Object
。
這給出了相互矛盾的方法
在Base public boolean removeArc(Object arc);
在Sub public Arc removeArc(Object value);
如果你做了
public interface Base<A extends Arc<?>> {
public boolean removeArc(A arc);
}
那么A
的實例將被替換為Arc
,並且方法簽名將不再沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.