如果有人能爲我解決這個難題。我相信我錯過了一些東西!Java通用轉換不如預期
interface a { }
class b implements a { }
class c extends ArrayList<b> { }
class d {
d(ArrayList<a> param) {}
}
class e {
public static void main(String[] arg) {
d newd = new d(new c());
}
}
此代碼有一個錯誤: 錯誤d(ArrayList<a>) is not applicable (actual argument c cannot be converted to ArrayList<a> by method invocation conversion)
當然類c
可以轉換爲ArrayList<a>
作爲c
延伸ArrayList<b>
和b
實現a
! 我試過顯式轉換,但沒有幫助。
它沒有意義要麼改變class c extends ArrayList<b>
到extends ArrayList<a>
爲c
的目的是的b
集合和接口a
只是用於顯示目的。另外類d
是一個通用顯示類,它依賴於接口a
中表示的功能,因此無法改變這一點。
建議會很方便!
你應該爲你的類使用大寫字母的名字,這樣看起來更難。 – 2013-02-20 15:46:05
喜歡繼承的組合(Effective Java 2 item 16)。 – nattyddubbs 2013-02-20 16:32:57