java开发实战经典(第二版)P217 6-6

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元

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值