【发布时间】:2020-07-28 01:23:58
【问题描述】:
所以我一直在从事一个项目,在该项目中我需要一个列表来填充其新的子类对象。
我已经用传统方法实现了,一个 ArrayList 将填充一种子类。但是为了使代码更短更高效,我正在考虑将 ArrayList 向下转换为有一个父类的 ArrayList,其中有两个子类对象。有可能吗?
这些是Things的父类
package Model;
public class Things {
protected String id;
protected String name;
protected double price;
protected int stock;
protected int bought;
public Things() {}
public Things(String id, String name, double price, int stock) {
this.id = id;
this.price = price;
this.name = name;
this.stock = stock;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getStock() {
return stock;
}
public void minusStock(int bought) {
this.stock = stock - bought;
}
}
这些是它的子类 Handphone and Vouchers
手机子类
package Model;
public class Handphone extends Things {
private String color;
public Handphone(String id, String name, double price, int stock, String color) {
super(id, name, price, stock);
this.color = color;
}
public String getColor() {
return color;
}
}
凭证子类
package Model;
public class Voucher extends Things {
private double tax;
public Voucher(String id, String name, double price, int stock, double tax) {
super(id, name, price, stock);
this.tax = tax;
}
public double getTax() {
return tax;
}
public double getsellingPrice() {
return (price + (price*tax));
}
}
所以提到主菜单界面会在不同的包上,我把import Model.*放在上面。如果我这样说,它是否也会包含在菜单包中?
【问题讨论】:
标签: java oop arraylist downcast upcasting