6.6 使用面向对象的概念表示出下面的生活场景:
小明去超市买东西,所有买到的东西都放在了购物车之中,最后到收银台一起结账。
package book;
interface Goods { // 使用接口表示商品
public double getPrice();
public String getName();
}
class Toys implements Goods { // 玩具区继承接口Goods
private String name;
private double price;
static String goodName = "玩具";
public double getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
Toys(String name, double price) {
this.name = name;
this.price = price;
}
};
class Clothes implements Goods { // 服装区
private String name;
private double price;
static String goodName = "服装";
public double getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
Clothes(String name, double price) {
this.name = name;
this.price = price;
}
};
class Drinks implements Goods { // 饮品区
private String name;
private double price;
static String goodName = "饮品";
public double getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
Drinks(String name, double price) {
this.name = name;
this.price = price;
}
};
class Foods implements Goods { // 食品区
private String name;
private double price;
static String goodName = "食品";
public double getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
Foods(String name, double price) {
this.name = name;
this.price = price;
}
};
class ShopTotal {
private Goods[] Good; // 模拟购物车
private int foot; // 购买的商品数量
private double total;
static int len = 5;
ShopTotal() {
this.Good = new Goods[len];
}
public void add(Goods good) {
if (this.foot >= this.Good.length) { // 当商品数大于购物车的容量就要进行扩容
Goods[] goods = new Goods[this.Good.length + len];
System.arraycopy(this.Good, 0, goods, 0, this.Good.length);
this.Good = goods;
}
this.Good[this.foot] = good;
this.foot++;
}
public double totalMoney() {
for (int i = 0; i < this.foot; i++) {
total += Good[i].getPrice();
}
return this.total;
}
public int getNumber() {
return this.foot;
}
};
public class JiOu {
public static void main(String args[]) {
ShopTotal st = new ShopTotal();
st.add(new Toys("手枪", 25.5));
st.add(new Toys("飞机", 84.3));
st.add(new Drinks("伊利(箱)", 73.5));
st.add(new Foods("乐事薯片", 8.5));
st.add(new Clothes("牛仔裤", 120));
st.add(new Clothes("白T", 60));
System.out.println("共购买" + st.getNumber() + "件商品,合计" + String.format("%.2f", st.totalMoney()) + "元");
}
}
运行结果:
共购买6件商品,合计371.80元