java实现简单的汽车租赁系统
时间: 2023-06-10 18:08:13 浏览: 121
下面是一个简单的汽车租赁系统的Java实现,主要包括车辆类(Vehicle)、租赁类(Rental)、客户类(Customer)和主类(Main)。
1. 车辆类(Vehicle)
```java
public class Vehicle {
private String make;
private String model;
private int year;
private double dailyRate;
private boolean rented;
public Vehicle(String make, String model, int year, double dailyRate) {
this.make = make;
this.model = model;
this.year = year;
this.dailyRate = dailyRate;
this.rented = false;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public double getDailyRate() {
return dailyRate;
}
public boolean isRented() {
return rented;
}
public void setRented(boolean rented) {
this.rented = rented;
}
}
```
2. 租赁类(Rental)
```java
public class Rental {
private Vehicle vehicle;
private int days;
public Rental(Vehicle vehicle, int days) {
this.vehicle = vehicle;
this.days = days;
}
public Vehicle getVehicle() {
return vehicle;
}
public int getDays() {
return days;
}
public double getRentalFee() {
return vehicle.getDailyRate() * days;
}
}
```
3. 客户类(Customer)
```java
import java.util.ArrayList;
import java.util.List;
public class Customer {
private String name;
private List<Rental> rentals;
public Customer(String name) {
this.name = name;
this.rentals = new ArrayList<>();
}
public String getName() {
return name;
}
public void rentVehicle(Vehicle vehicle, int days) {
if (!vehicle.isRented()) {
Rental rental = new Rental(vehicle, days);
rentals.add(rental);
vehicle.setRented(true);
} else {
System.out.println("Vehicle is already rented.");
}
}
public double getTotalRentalFee() {
double totalFee = 0.0;
for (Rental rental : rentals) {
totalFee += rental.getRentalFee();
}
return totalFee;
}
}
```
4. 主类(Main)
```java
public class Main {
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle("Toyota", "Camry", 2020, 50.0);
Vehicle vehicle2 = new Vehicle("Honda", "Accord", 2021, 60.0);
Customer customer1 = new Customer("John");
customer1.rentVehicle(vehicle1, 3);
customer1.rentVehicle(vehicle2, 5);
System.out.println(customer1.getName() + " rented " + vehicle1.getMake() + " " + vehicle1.getModel() +
" for " + customer1.getTotalRentalFee() + " dollars.");
Customer customer2 = new Customer("Mary");
customer2.rentVehicle(vehicle2, 2);
System.out.println(customer2.getName() + " rented " + vehicle2.getMake() + " " + vehicle2.getModel() +
" for " + customer2.getTotalRentalFee() + " dollars.");
}
}
```
该系统通过创建Vehicle、Rental和Customer对象实现了车辆租赁的基本功能,同时对于每个车辆进行了状态管理,避免了重复租赁。