用Java编写(1)通过任务描述可知,该系统中必须包括3个实体类,类名及属性设置如下: 1.食材类(Food): a)食材编号(id) b)食材名称(name) c)食材单价(price) d)库存数量(storage) 2.订单项类(OrderItem): a)食材(food) b)购买数量(num) 3.订单类(Order): a)订单号(orderID) b)订单总额(total) c)订单项列表(items) (2)由于购买食材时,需要选择食材的数量,所以需要在订单项类里定义获取食材对象以及食材数量的方法。 (3)由于需要指定订单项以及获取订单的订单列表、订单号、订单总额等信息,所以需要有订单列表、订单号、订单总额指定订单项等方法。
时间: 2023-06-24 14:04:58 浏览: 83
下面是用Java编写的实现:
1. 食材类(Food)
```java
public class Food {
private int id;
private String name;
private double price;
private int storage;
public Food(int id, String name, double price, int storage) {
this.id = id;
this.name = name;
this.price = price;
this.storage = storage;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
}
```
2. 订单项类(OrderItem)
```java
public class OrderItem {
private Food food;
private int num;
public OrderItem(Food food, int num) {
this.food = food;
this.num = num;
}
public Food getFood() {
return food;
}
public int getNum() {
return num;
}
public double getItemPrice() {
return food.getPrice() * num;
}
}
```
3. 订单类(Order)
```java
import java.util.ArrayList;
import java.util.List;
public class Order {
private int orderID;
private double total;
private List<OrderItem> items;
public Order(int orderID) {
this.orderID = orderID;
this.total = 0;
this.items = new ArrayList<>();
}
public int getOrderID() {
return orderID;
}
public double getTotal() {
return total;
}
public List<OrderItem> getItems() {
return items;
}
public void addItem(OrderItem item) {
items.add(item);
total += item.getItemPrice();
}
}
```
在以上代码中,食材类(Food)包含了食材的编号、名称、单价和库存数量属性,订单项类(OrderItem)包含了食材对象以及食材数量,订单类(Order)包含了订单号、订单总额和订单项列表属性。在订单项类中,通过getItemPrice方法计算出订单项的总价,添加到订单总额中。
阅读全文