【发布时间】:2017-03-26 03:16:58
【问题描述】:
我正在编写一个具有不同类的程序,并且有一个集合类,它只存储超类的子类。
好的,所以我有一个 Order 超级类来存储数量。代码sn-p是这样的:
abstract class Order { //superclass
private int quantity; //instance variables
public Items(int quantity) { //constructor
this.quantity = quantity;
}
public int getQuantity() { // instance method
return quantity;
}
public abstract double totalPrice();
然后我有order 类的子类。子类如下。
class Coffee extends Order { //subclass
private String size; //instance variables
public Coffee (int quantity, String size) { //constructor
super(quantity);
this.size = size;
} //... some other methods
} // end of Coffee class
class Donuts extends Order { //sub-class
private double price; //instance variables
private String flavour;
public Donuts(int quantity, double price, String flavour) { //constructor
super(quantity);
this.price = price;
this.flavour = flavour;
} //...some other methods
} //end of donut class
class Pop extends Order {
private String size;
private String brand;
public Pop(int quantity, String size, String brand) {
super(quantity);
this.size = size;
this.brand = brand;
} //...again there are some other methods
} //end of pop sub-class
现在这是我需要帮助的地方。我编写了一个包含ArrayList<> 的集合类。代码sn-p是这样的:
class OrderList {
private ArrayList<Order> list;
public OrderList() {
list = new ArrayList<Order>();
}
我想要在集合类中做的是拥有确保只有子类只添加到我的集合类中的实例方法。*
到目前为止我尝试过的是这个(这让我完全是个傻瓜,我知道)。
public void add(Coffee cof) {
list.add(cof);
}
public void add(Donut don) { // i know we cant have methods with the same name
list.add(don);
}
public void add(Sandwich sand) {
list.add(sand);
}
public void add(Pop p) {
list.add(p);
}
SO 社区,您能否就我的问题给我一些提示。
【问题讨论】:
-
我准备提供更多细节。
-
嗯,它永远是一个子类,因为你不能实例化一个抽象类
-
您只想添加特定的子类吗?
-
你可以拥有同名的方法,重要的是签名。
-
您只需要一个
add(Order order)方法。由于 Order 是抽象的,您不能直接创建“Order”对象;它只能通过子类创建。 (我假设@flakes 的意思是 can't,而不是 can。)
标签: java class inheritance arraylist collections