小明去超市买东西,所有买到的东西都放在了购物车中,最后到收银台一起结账。
1、定义出一个商品的标准
public interface IGoods { //定义商品标准
public String getName();
public double getPrice();
}
2、定义购物车处理标准
public interface IShopCar { //购物车
public void add(IGoods goods); //添加商品信息
public void delete(IGoods goods); //删除商品
public Object [] getAll(); //获得购物车中全部商品信息
}
3、定义一个购物车的实现类
public class ShopCarImpl implements IShopCar { //购物车实现类
private ILink<IGoods> allGoods=new Link<IGoods>();
@Override
public void add(IGoods goods) {
this.allGoods .add(goods);
}
@Override
public void delete(IGoods goods) {
this.allGoods .remove(goods);
}
@Override
public Object[] getAll() {
return this.allGoods .toArray();
}
}
4、定义收银台
public class Cashier { //收银台
private IShopCar shpocar;
public Cashier(IShopCar shpocar) {
this.shpocar = shpocar;
}
public double allPrice() { //计算总价
double all=0.0;
Object [] result=this.shpocar .getAll();
for(Object obj:result) {
IGoods goods=(IGoods)obj;
all+=goods.getPrice();
}
return all;
}
public int allCount() { //商品数量
return this.shpocar.getAll().length;
}
}
5、定义商品信息
图书
public class Book implements IGoods {
private String name;
private double price;
@Override
public String getName() {
return this.name;
}
@Override
public double getPrice() {
return this.price;
}
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(this==obj) {
return true;
}
if(!(obj instanceof Book)) {
return false;
}
Book book=(Book)obj;
return this.name.equals(book.name)&&this.price==book.price;
}
@Override
public String toString() {
return "图书 [name=" + name + ", price=" + price + "]";
}
}
书本
public class Bag implements IGoods {
private String name;
private double price;
@Override
public String getName() {
return this.name;
}
@Override
public double getPrice() {
return this.price;
}
public Bag(String name, double price) {
this.name = name;
this.price = price;
}
public boolean equals(Object obj) {
if(obj==null) {
return false;
}
if(this==obj) {
return true;
}
if(!(obj instanceof Bag)) {
return false;
}
Bag bag=(Bag)obj;
return this.name.equals(bag.name)&&this.price==bag.price;
}
@Override
public String toString() {
return "背包 [name=" + name + ", price=" + price + "]";
}
}
6、测试
public class ShopDemo {
public static void main(String[] args) {
IShopCar car=new ShopCarImpl();
car.add(new Book("java开发",50.80));
car.add(new Book("MySql开发",58.80));
car.add(new Bag("布包",10.80));
car.add(new Bag("书包",20.80));
Cashier cas=new Cashier(car);
System.out.println("商品价格"+cas.allPrice()+"、购买数量"+cas.allCount());
}
}
执行结果
商品价格141.2、购买数量4
1、 内部类的主要特点是可以与外部类之间进行私有属性的互访问。 ( √)
2、 使用static定义的内部类就是外部类,该内部类可以直接访问外部类中的非static成员属性。 ( × )
3、 匿名内部类主要功能是可以直接进行接口和抽象类的对象实例化处理。 ( √ )
4、 Lambda表达式是一种简化接口子类的处理,接口中的方法数量可以随意定义。 ( × )
5、 函数式接口必须使用“@FunctionalInterface”定义,否则不生效。 ( ×)
6、 使用static定义的内部类就成为外部类。 ( √ )