假设我扩展 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
最佳答案
使用 GroceryItem
类型扩展 LinkedList
public class GroceryList extends LinkedList<GroceryItem>
或者使用以下方法将类定义为通用类:
public class GroceryList<T extends GroceryItem> extends LinkedList<T>
关于java - 如果我使用类作为类型参数,如何在参数化类中创建该对象的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071342/