2013-09-28 49 views
0


假設我假設延伸LinkedList創建一個稱爲GroceryList的專門子類。

GroceryList參數化爲GroceryItem作爲其類型。

當我嘗試訪問GroceryItem作爲內GroceryList一個實例,我得到這個編譯錯誤在NetBeans:如果我使用類作爲類型參數,如何在參數化類中創建此對象的實例?

incompatible types 
Required: GroceryItem 
Found: Object 
where GroceryItem is a type-variable 
    GroceryItem extends Object declared in class GroceryList 


顯然,這是由於「類型擦除」,到目前爲止我米在使用類既不成功「類型變量」並且以這種方式的一類...



下面是一個簡單的例子:

public class GroceryList<GroceryItem> extends LinkedList { 

    public GroceryList() { 
    } 

    public double getItemPrice(GroceryItem item) { 

     // compile-error occurring here: 
     return item.getPrice(); 
    } 

    // compile-error occurring here: 
    public GroceryItem getGroceryItem(String name, String brand, double price) { 

     // ...finding the grocery item based on the parameters here: 
     // ... 

     return item; 
    } 
} // end of class 
+5

你聲明與名稱'GroceryItem'類型參數。這隱藏了你的'GroceryItem'類型。 –

+0

你能顯示GroceryItem代碼嗎?粘貼確切的錯誤?只是快速評論,getItemPrice可能是靜態的,因爲你沒有使用你自己的類中的任何東西。 – porfiriopartida

+4

嘗試'公共類GroceryList擴展LinkedList ' – Reimeus

回答

3

使用GroceryItem

public class GroceryList extends LinkedList<GroceryItem> 

擴展LinkedList或使用類定義爲通用:

public class GroceryList<T extends GroceryItem> extends LinkedList<T> 
+2

+1此外,'類GroceryList 擴展LinkedList '會工作,如果類需要是通用的。 –

+0

當然。繼續 :) –

相關問題