《JAVA开发实战经典》P239练习
6.使用面向对象的概念表示出下面的生活场景:
小明去超市买东西,所有买到的东西都放在了购物车当中,最后到收银台一起结账。
快捷键
interface Goods{
public String getName();
public double getPrice();
}
class Toys implements Goods{
private String name;
private double price;
public String getName() {
return this.name;
}
public double getPrice(){
return this.price;
}
Toys(String name,double price){
this.name = name;
this.price = price;
}
}
class Clothes implements Goods{
private String name;
private double price;
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;
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;
public double getPrice(){
return this.price;
}
public String getName() {
return this.name;
}
Foods(String name,double price){
this.name = name;
this.price = price;
}
}
class ShoppingCart{
private Goods Good[];
private int foot;
static int addlen = 1;
private double total;
public ShoppingCart(int len){
if (len > 1){
Good = new Goods[len];
}else{
Good = new Goods[1];
}
}
//定义购物篮大小,添加商品
public void add(Goods good){
if (this.foot >= Good.length){
Goods goods[] = new Goods[this.Good.length + addlen];
System.arraycopy(this.Good,0,goods,0,this.Good.length);
this.Good = goods;
}
this.Good[this.foot] = good;
foot++;
}
//计算总价
public double totalMoney(){
for (int i = 0; i < Good.length; i++) {
total += Good[i].getPrice();
}
return this.total;
}
//计总件数
public int totalCount(){
return foot;
}
}
public class Main{
public static void main(String[] args) {
ShoppingCart sc = new ShoppingCart(1);
sc.add(new Toys("手枪",25.5));
sc.add(new Toys("飞机",84.3));
sc.add(new Drinks("特伦舒(箱)",73.5));
sc.add(new Foods("乐事薯片",8.5));
sc.add(new Clothes("牛仔裤",120));
sc.add(new Clothes("白T",60));
System.out.println("总共买了" + sc.totalCount() + "商品" + ";共计" + sc.totalMoney() + "元");
}
}