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.

113 lines
3.4 KiB

public class Car {
// 1. 私有属性
private final String licensePlate; // 车牌号(不可变)
private String brand; // 品牌
private String model; // 型号
private double dailyRent; // 日租金
private boolean isRented; // 是否已出租
// 静态变量:统计车辆总数
private static int totalCars = 0;
// 2. 全参构造方法
public Car(String licensePlate, String brand, String model, double dailyRent) {
this.licensePlate = licensePlate;
this.brand = brand;
this.model = model;
setDailyRent(dailyRent); // 通过setter校验租金
this.isRented = false; // 初始状态:未出租
totalCars++; // 每创建一个对象,总数+1
}
// 3. 三参构造方法(调用全参构造,日租金默认300元)
public Car(String licensePlate, String brand, String model) {
this(licensePlate, brand, model, 300.0);
}
// 4. Getter/Setter 方法
public String getLicensePlate() {
return licensePlate;
}
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;
}
// 日租金 setter:必须校验是否大于0
public void setDailyRent(double dailyRent) {
if (dailyRent > 0) {
this.dailyRent = dailyRent;
} else {
System.out.println("日租金必须大于0,设置失败!");
}
}
public boolean isRented() {
return isRented;
}
// 注意:isRented 不提供 setter,只能通过业务方法修改状态
// 5. 业务方法
// 租车:将状态置为已出租
public void rentCar() {
if (isRented) {
System.out.println("车辆 " + licensePlate + " 已出租,无法再次租用!");
} else {
isRented = true;
System.out.println("车辆 " + licensePlate + " 已成功出租!");
}
}
// 还车:将状态置为未出租
public void returnCar() {
if (!isRented) {
System.out.println("车辆 " + licensePlate + " 未被租用,无需归还!");
} else {
isRented = false;
System.out.println("车辆 " + licensePlate + " 已成功归还!");
}
}
// 计算总租金:日租金 × 天数(假设天数>0)
public double calculateRent(int days) {
if (days > 0) {
return dailyRent * days;
} else {
System.out.println("租赁天数必须大于0!");
return 0.0;
}
}
// 6. 静态方法:获取总车辆数
public static int getTotalCars() {
return totalCars;
}
// 辅助方法:打印车辆信息
public void displayInfo() {
System.out.println("=== 车辆信息 ===");
System.out.println("车牌号:" + licensePlate);
System.out.println("品牌:" + brand);
System.out.println("型号:" + model);
System.out.println("日租金:" + dailyRent + " 元/天");
System.out.println("状态:" + (isRented ? "已出租" : "可租"));
System.out.println("================");
}
}