我有一个名为GenericOrder的基类,可用于创建任何类型产品的订单,然后我有更具体的订单的子类.我的问题是我的ComputerOrder类和一个我要覆盖的方法.这是基类代码.
import java.util.List; import java.util.ArrayList; public class GenericOrder{ private long orderNumber; private List products; private T theClass; public GenericOrder() { products = new ArrayList (); orderNumber = System.currentTimeMillis(); } public long getOrderNumber() { return orderNumber; } public void addProduct(T newProduct) { products.add(newProduct); } public int getNumberOfProducts() { return products.size(); } public List getProducts() { return products; } public void setProducts(List products) { this.products = products; } public T get() { return theClass; } public void set(T theClass) { this.theClass = theClass; } }
这是我的子类代码.getProducts是我遇到问题的方法.
import java.util.ArrayList; import java.util.List; public class ComputerOrderextends GenericOrder { private List computerParts = new ArrayList (); private String orderType = "Computer Parts"; public ComputerOrder() { super(); } public void addProduct(ComputerPart newProduct) { computerParts.add(newProduct); } public String getOrderType() { return orderType; } public int getNumberOfProducts() { return computerParts.size(); } public List getProducts() { return computerParts; } }
我得到的错误说不能转换List(ComputerPart)
为List
错误非常明确:getProducts()
声明返回a List
但你正在返回a List
.我认为我们同意这两者并不相同.
看看你的代码看起来你实际上不需要泛型类,因为ComputerOrder
只接受ComputerPart
s.你想要的是如下:
public class ComputerOrder extends GenericOrder{ @Override public List getProducts() { return computerParts; } }