java用面对对象的方式做一个自助车辆管理系统
时间: 2024-10-13 07:09:07 浏览: 30
要使用 Java 的面向对象思想构建一个简单的自助车辆管理系统的框架,我们可以设计以下几个关键类:
1. **车辆类(Vehicle)**:
- 属性: 车牌号(plateNumber), 车型(model), 颜色(color), 状态(status)(例如:可用、已租)
- 方法: 获取信息(getInfo()), 租车(reserve()), 归还车(returnCar())
```java
public class Vehicle {
private String plateNumber;
private String model;
private String color;
private String status;
public Vehicle(String plateNumber, String model, String color) {
this.plateNumber = plateNumber;
this.model = model;
this.color = color;
this.status = "Available";
}
public String getInfo() {
return "车牌号: " + plateNumber + ", 模型: " + model + ", 颜色: " + color + ", 状态: " + status;
}
public boolean reserve() {
// 检查车辆状态并更新
if ("Available".equals(status)) {
status = "Reserved";
return true;
} else {
return false;
}
}
public void returnCar() {
if ("Reserved".equals(status)) {
status = "Available";
} else {
System.out.println("车辆未处于已租状态,无法归还");
}
}
}
```
2. **租车站(Classroom)**:
- 属性: 车辆集合(vehicleList)
- 方法: 添加车辆(addVehicle), 租车租赁(rentVehicle), 更新车辆状态(updateStatus)
```java
import java.util.ArrayList;
import java.util.List;
public class CarRentalStation {
private List<Vehicle> vehicleList;
public CarRentalStation() {
vehicleList = new ArrayList<>();
}
public void addVehicle(Vehicle vehicle) {
vehicleList.add(vehicle);
}
public Vehicle rentVehicle(String plateNumber) {
for (Vehicle vehicle : vehicleList) {
if (vehicle.getPlateNumber().equals(plateNumber) && vehicle.reserve()) {
return vehicle;
}
}
throw new IllegalArgumentException("车辆不存在或已被租借");
}
public void updateStatus(String plateNumber, String newStatus) {
for (Vehicle vehicle : vehicleList) {
if (vehicle.getPlateNumber().equals(plateNumber)) {
vehicle.returnCar(); // 先还原,再更新
vehicle.setStatus(newStatus);
break;
}
}
}
}
```
3. **主程序(Main Class)**:
- 创建车辆和租车站实例,进行操作
```java
public class Main {
public static void main(String[] args) {
CarRentalStation station = new CarRentalStation();
Vehicle car1 = new Vehicle("ABC123", "Toyota", "Blue");
// 添加车辆
station.addVehicle(car1);
// 租车
try {
Vehicle rentedCar = station.rentVehicle("ABC123");
System.out.println(rentedCar.getInfo());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
// 归还车辆
station.updateStatus("ABC123", "Available");
}
}
```
这只是一个基础的框架,实际系统可能需要添加用户认证、数据库集成、错误处理等功能。
阅读全文