package com.jsu.money;
//假设你正在设计一个咖啡店的点单系统,要求实现以下功能:
//
//定义一个接口Beverage,包含方法getDescription()用于获取饮料描述和getCost()用于获取饮料价格。
//创建两个类Coffee和Tea,分别实现Beverage接口,其中Coffee代表咖啡,Tea代表茶,它们都有描述和价格属性。
//在主函数中,创建一个ArrayList用于存储不同的饮料对象(可以包括多杯咖啡和茶)。
//遍历ArrayList,输出每种饮料的描述和价格。
//计算所有饮料的总价格并输出。
public interface Beverage {
String getDescription();//获取饮料描述
Double getCost(); //获取饮料价格
}
package com.jsu.money;
public class Coffee implements Beverage{
private String Description;
public Double Cost;
public Coffee(String description, Double cost) {
Description = description;
Cost = cost;
}
@Override
public String getDescription() {
return Description;
}
@Override
public Double getCost() {
return Cost;
}
}
package com.jsu.money;
public class Tea implements Beverage{
private String description;
private Double cost;
public Tea(String description, Double cost) {
this.description = description;
this.cost = cost;
}
@Override
public String getDescription() {
return description;
}
@Override
public Double getCost() {
return cost;
}
}
package com.jsu.money;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Beverage> beverages = new ArrayList<>();
beverages.add(new Coffee("拿铁", 20.0));
beverages.add(new Tea("龙井",12.0));
double totalCost = 0;
for (int i = 0; i < beverages.size(); i++) {
Beverage beverage = beverages.get(i);
System.out.println("饮料描述:" + beverage.getDescription());
System.out.println("价格:" + beverage.getCost());
totalCost += beverage.getCost();
}
System.out.println("总价格:" + totalCost);
}
}
运行结果为:
饮料描述:拿铁
价格:20.0
饮料描述:龙井
价格:12.0
总价格:32.0