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.

117 lines
3.3 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;
this.dailyRent = dailyRent;
this.isRented = false; // 初始状态:未出租
totalCars++; // 每创建一个对象,总数+1
}
// 重载构造方法:只接收车牌号、品牌、型号,日租金默认300
public Car(String licensePlate, String brand, String model) {
this(licensePlate, brand, model, 300.0); // 调用全参构造
}
// 3. Getter/Setter 方法
public String getLicensePlate() {
return licensePlate;
}
// 无setLicensePlate,保证车牌号不可修改
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,修改无效。");
}
}
public boolean isRented() {
return isRented;
}
// 无setIsRented,状态必须通过业务方法改变
// 静态方法:获取总车辆数
public static int getTotalCars() {
return totalCars;
}
// 4. 业务方法
/**
* 租车:将车辆状态置为已出租
*/
public void rentCar() {
if (isRented) {
System.out.println("车辆已租出,无法再次租用。");
} else {
isRented = true;
System.out.println("租车成功:" + licensePlate);
}
}
/**
* 还车:将车辆状态置为未出租
*/
public void returnCar() {
if (!isRented) {
System.out.println("车辆未被租用,无需归还。");
} else {
isRented = false;
System.out.println("还车成功:" + licensePlate);
}
}
/**
* 计算总租金
* @param days 租用天数(假设>0,不做校验)
* @return 总租金
*/
public double calculateRent(int days) {
return dailyRent * days;
}
// 辅助方法:显示车辆信息
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();
}
}