[英]If I use a class as a type parameter, how can I create an instance of this object within the parameterized class?
假設我假設擴展LinkedList
以創建一個名為GroceryList
的專門子類。
使用類GroceryItem
作為其類型對GroceryList
進行參數化。
當我嘗試在GroceryList
作為實例訪問GroceryItem
,在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
使用GroceryItem
類型擴展LinkedList
public class GroceryList extends LinkedList<GroceryItem>
或使用以下方法將類定義為泛型:
public class GroceryList<T extends GroceryItem> extends LinkedList<T>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.