Java如何将集合加入面板_java – 仅将子类实例添加到我的集合类中

我正在编写一个包含不同类的程序,并且有一个集合类,它只存储超类的子类.

好的,所以我有一个存储数量的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社区可以请你给我一些关于我的问题的提示.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值