我正在编写一个包含不同类的程序,并且有一个集合类,它只存储超类的子类.
好的,所以我有一个存储数量的Order超级类.代码片段如下:
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();
然后我有订单类的子类.子类如下.
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<>的集合类.代码片段是这样的:
class OrderList {
private ArrayList list;
public OrderList() {
list = new ArrayList();
}
我想在集合类中做的是让实例方法确保只将子类添加到我的集合类中.*
到目前为止我所尝试的是这个(这让我变得完全傻瓜,我知道).
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社区可以请你给我一些关于我的问题的提示.