You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

142 lines
4.5 KiB

package com.rental;
public class Car {
// 1. 私有属性
private final String licensePlate; // 车牌号,使用 final 确保不可变
private String brand;
private String model;
private double dailyRent;
private boolean isRented;
// 5. 静态成员(加分项)
private static int totalCars = 0; // 用于统计创建的车辆总数
// 2. 构造方法
/**
* 全参构造方法
* @param licensePlate 车牌号
* @param brand 品牌
* @param model 型号
* @param dailyRent 日租金
*/
public Car(String licensePlate, String brand, String model, double dailyRent) {
this.licensePlate = licensePlate;
this.brand = brand;
this.model = model;
// 调用 setter 以进行租金校验
this.setDailyRent(dailyRent);
this.isRented = false; // 初始化为未租出
totalCars++; // 创建对象时,总数加1
}
/**
* 部分参数构造方法(车牌、品牌、型号)
* 日租金默认为 300.0
* @param licensePlate 车牌号
* @param brand 品牌
* @param model 型号
*/
public Car(String licensePlate, String brand, String model) {
// 使用 this() 调用全参构造方法
this(licensePlate, brand, model, 300.0);
}
// 3. Getter 和 Setter 方法
public String getLicensePlate() {
return licensePlate;
}
// 车牌号没有 setter
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getDailyRent() {
return dailyRent;
}
public void setDailyRent(double dailyRent) {
// 数据校验:日租金必须大于0
if (dailyRent > 0) {
this.dailyRent = dailyRent;
} else {
System.out.println("[警告] 日租金必须大于0,修改失败。当前值保持为:" + this.dailyRent);
}
}
public boolean isRented() {
return isRented;
}
// isRented 没有 setter,状态必须通过业务方法改变
// 4. 业务方法
/**
* 租车方法
*/
public void rentCar() {
if (!this.isRented) {
this.isRented = true;
System.out.println("车牌号 " + this.licensePlate + " 的车辆已成功租出。");
} else {
System.out.println("车辆已租出,无法再次租用。");
}
}
/**
* 还车方法
*/
public void returnCar() {
if (this.isRented) {
this.isRented = false;
System.out.println("车牌号 " + this.licensePlate + " 的车辆已成功归还。");
} else {
System.out.println("车辆未被租用,无需归还。");
}
}
/**
* 计算租金
* @param days 租用天数
* @return 总租金
*/
public double calculateRent(int days) {
// 假设 days 参数合法(>0),按作业要求暂不校验
return this.dailyRent * days;
}
// 5. 静态方法
/**
* 获取创建的车辆总数
* @return 车辆总数
*/
public static int getTotalCars() {
return totalCars;
}
// 可选:一个用于打印车辆信息的方法,便于测试
/**
* 显示车辆信息
*/
public void displayInfo() {
String status = this.isRented ? "已租出" : "可租";
System.out.println("=== 车辆信息 ===");
System.out.println("车牌号: " + this.licensePlate);
System.out.println("品牌型号: " + this.brand + " - " + this.model);
System.out.printf("日租金: %.2f 元/天\n", this.dailyRent);
System.out.println("状态: " + status);
System.out.println("=================");
}
}