繁体   English   中英

如果将类用作类型参数,如何在参数化的类中创建此对象的实例?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM