淘先锋技术网

首页 1 2 3 4 5 6 7

Java订餐系统类和对象是管理餐厅订单以及菜单的系统。

在Java中,类是一个蓝图,它用于描述对象的属性和方法。而对象则是类的实例,并且可以拥有自己的属性和方法。

在订餐系统中,需要定义以下类:

public class MenuItem {
private String name;
private String description;
private double price;
public MenuItem(String name, String description, double price) {
this.name = name;
this.description = description;
this.price = price;
}
// Getters and setters for the private fields
}
public class Menu {
private ArrayListmenuItems;
public Menu() {
this.menuItems = new ArrayList();
}
public void addMenuItem(MenuItem menuItem) {
this.menuItems.add(menuItem);
}
public void removeMenuItem(MenuItem menuItem) {
this.menuItems.remove(menuItem);
}
// Getter for menuItems
}
public class Order {
private ArrayListitems;
private double totalPrice;
public Order() {
this.items = new ArrayList();
this.totalPrice = 0.0;
}
public void addItem(MenuItem menuItem) {
this.items.add(menuItem);
this.totalPrice += menuItem.getPrice();
}
public void removeItem(MenuItem menuItem) {
this.items.remove(menuItem);
this.totalPrice -= menuItem.getPrice();
}
public double getTotalPrice() {
return this.totalPrice;
}
// Getter for items
}
public class Restaurant {
private Menu menu;
public Restaurant() {
this.menu = new Menu();
}
public void addMenuItem(MenuItem menuItem) {
this.menu.addMenuItem(menuItem);
}
public void removeMenuItem(MenuItem menuItem) {
this.menu.removeMenuItem(menuItem);
}
public Order createOrder() {
return new Order();
}
}
public class Main {
public static void main(String[] args) {
Restaurant restaurant = new Restaurant();
MenuItem menuItem1 = new MenuItem("Spaghetti Carbonara", "Pasta with bacon and egg", 12.99);
MenuItem menuItem2 = new MenuItem("Margherita Pizza", "Pizza with tomato sauce and mozzarella", 10.99);
restaurant.addMenuItem(menuItem1);
restaurant.addMenuItem(menuItem2);
Order order = restaurant.createOrder();
order.addItem(menuItem1);
order.addItem(menuItem2);
System.out.println("Total price of order: " + order.getTotalPrice());
}
}

以上类定义了菜单、菜单项、订单和餐厅四个类,并且在主函数中创建餐厅、菜单项以及订单,并且添加菜单项到订单中,最终输出订单的总价格。通过这些类和对象的定义,可以实现一个完整的订餐系统。