请给我写一个Java面向对象点餐系统 要求用到类和对象,抽象,用到继承和多态,用到ArrayList或者HashMap,把测试类也打出来,并解释代码
时间: 2023-10-05 16:08:16 浏览: 96
好的,以下是一个简单的Java面向对象点餐系统示例:
```
import java.util.ArrayList;
import java.util.HashMap;
// 菜品类
class Dish {
private String name;
private double price;
public Dish(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
// 套餐类
class SetMeal extends Dish {
private ArrayList<Dish> dishes;
public SetMeal(String name, double price) {
super(name, price);
dishes = new ArrayList<>();
}
public void addDish(Dish dish) {
dishes.add(dish);
}
public ArrayList<Dish> getDishes() {
return dishes;
}
}
// 订单类
class Order {
private HashMap<Dish, Integer> items;
public Order() {
items = new HashMap<>();
}
public void addItem(Dish dish, int quantity) {
if (items.containsKey(dish)) {
items.put(dish, items.get(dish) + quantity);
} else {
items.put(dish, quantity);
}
}
public double getTotalPrice() {
double totalPrice = 0;
for (Dish dish : items.keySet()) {
totalPrice += dish.getPrice() * items.get(dish);
}
return totalPrice;
}
}
public class Restaurant {
public static void main(String[] args) {
// 创建菜单
Dish hotpot = new Dish("火锅", 88.8);
Dish chicken = new Dish("鸡肉卷", 18.8);
Dish beef = new Dish("牛肉卷", 28.8);
SetMeal set1 = new SetMeal("超值套餐1", 48.8);
set1.addDish(hotpot);
set1.addDish(chicken);
SetMeal set2 = new SetMeal("豪华套餐2", 108.8);
set2.addDish(hotpot);
set2.addDish(chicken);
set2.addDish(beef);
// 提示客户点餐
System.out.println("欢迎光临,请点餐:");
// 创建订单
Order order = new Order();
// 客户点餐
order.addItem(hotpot, 1);
order.addItem(set1, 2);
// 打印订单详情
System.out.println("您的订单:");
for (Dish dish : order.getItems().keySet()) {
int quantity = order.getItems().get(dish);
System.out.println(dish.getName() + " x " + quantity + " = " + dish.getPrice() * quantity);
}
System.out.println("总价:" + order.getTotalPrice());
}
}
```
这个点餐系统包含菜品类、套餐类和订单类,其中套餐类继承了菜品类,而订单类包含了多个菜品或套餐,并且使用了HashMap来记录每个菜品或套餐的数量。测试类中首先创建了一些菜品和套餐,然后客户点了一些菜品和套餐,最后打印出订单详情和总价。这个示例使用了类和对象、抽象、继承和多态,以及ArrayList或HashMap来存储数据。
阅读全文