,同時爲了減少在我的項目的代碼複製推廣一些類我有一個錯誤,情況如下:Java泛型和多態性
interface ClassRoot{}
public class ClassChild1 implements ClassRoot{
// constructor is omitted for simplicity
public Collection<ClassChild1> createList(){
Collection<ClassChild1> col = getCollectionFromSomewhere();
return col;
}
}
public class Class1{
protected <T extends ClassRoot> Collection<T> doSth(){
Collection<T> myCol = null;
ClassChild1 child = new ClassChild1();
// here I get compile time assignment error
// also (assuming that myCol not null) myCol.add(new ClassChild1());
// is not permitted.
myCol = child.createList();
return myCol;
}
}
是不是對多態現象?我知道,例如,
List<Object> list1;
永遠不能(也不應該被指定爲類型安全)到:
List<String> list2;
但在這裏我的情況是不同的,我指定的類型參數擴展一些特定的類希望利用OOP多態概念,做好正確實施正確課程的作業。 現在我有2個問題;
- 有人可以清楚地解釋爲什麼這是禁止在Java中,爲什麼有正當理由?
- 如何通過使用類型參數或通配符來實現這樣的功能?
createList()應返回Collection而不是ClassChild1。你沒有編譯錯誤嗎? 爲了清楚起見,您應該在您的問題中解釋您的錯誤,而不僅僅是代碼註釋。 –
kgautron
2012-08-01 08:47:20
編輯爲公開收藏 createList()。 –
px5x2
2012-08-01 10:12:03