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.
112 lines
3.7 KiB
112 lines
3.7 KiB
|
|
public class Car {
|
|
// 1. 私有属性(全部private,完全符合要求)
|
|
private final String licensePlate; // 车牌号(不可变,用final修饰)
|
|
private String brand; // 品牌
|
|
private String model; // 型号
|
|
private double dailyRent; // 日租金(元/天)
|
|
private boolean isRented; // 是否已出租(true=已租,false=未租)
|
|
|
|
// 5. 静态成员:统计车辆总数(选做加分项,直接实现)
|
|
private static int totalCars = 0;
|
|
|
|
// 2. 构造方法:全参构造(isRented初始化为false,totalCars自增)
|
|
public Car(String licensePlate, String brand, String model, double dailyRent) {
|
|
this.licensePlate = licensePlate;
|
|
this.brand = brand;
|
|
this.model = model;
|
|
// 日租金校验:如果传入非法值,用默认300
|
|
if (dailyRent > 0) {
|
|
this.dailyRent = dailyRent;
|
|
} else {
|
|
this.dailyRent = 300.0;
|
|
System.out.println("警告:日租金必须大于0,已自动设置为默认值300元/天");
|
|
}
|
|
this.isRented = false; // 初始未出租
|
|
totalCars++; // 每创建一个对象,总数+1
|
|
}
|
|
|
|
// 2. 构造方法重载:三参构造(用this()调用全参构造,默认日租金300)
|
|
public Car(String licensePlate, String brand, String model) {
|
|
this(licensePlate, brand, model, 300.0); // 调用全参构造
|
|
}
|
|
|
|
// 3. Getter/Setter(严格符合要求)
|
|
// 车牌号:只提供getter,无setter(不可修改)
|
|
public String getLicensePlate() {
|
|
return licensePlate;
|
|
}
|
|
|
|
// 品牌:getter+setter
|
|
public String getBrand() {
|
|
return brand;
|
|
}
|
|
public void setBrand(String brand) {
|
|
this.brand = brand;
|
|
}
|
|
|
|
// 型号:getter+setter
|
|
public String getModel() {
|
|
return model;
|
|
}
|
|
public void setModel(String model) {
|
|
this.model = model;
|
|
}
|
|
|
|
// 日租金:getter+setter,setter必须校验>0
|
|
public double getDailyRent() {
|
|
return dailyRent;
|
|
}
|
|
public void setDailyRent(double dailyRent) {
|
|
if (dailyRent > 0) {
|
|
this.dailyRent = dailyRent;
|
|
} else {
|
|
System.out.println("错误:日租金必须大于0,修改失败,保持原值:" + this.dailyRent);
|
|
}
|
|
}
|
|
|
|
// 出租状态:只提供getter(isRented()),无setter(只能通过业务方法修改)
|
|
public boolean isRented() {
|
|
return isRented;
|
|
}
|
|
|
|
// 5. 静态方法:获取车辆总数
|
|
public static int getTotalCars() {
|
|
return totalCars;
|
|
}
|
|
|
|
// 4. 业务方法:租车
|
|
public void rentCar() {
|
|
if (isRented) {
|
|
System.out.println("车辆已租出,无法再次租用");
|
|
} else {
|
|
isRented = true;
|
|
System.out.println("车辆已成功租出");
|
|
}
|
|
}
|
|
|
|
// 4. 业务方法:还车
|
|
public void returnCar() {
|
|
if (!isRented) {
|
|
System.out.println("车辆未被租用,无需归还");
|
|
} else {
|
|
isRented = false;
|
|
System.out.println("车辆已成功归还");
|
|
}
|
|
}
|
|
|
|
// 4. 业务方法:计算租金(仅计算,不修改属性)
|
|
public double calculateRent(int days) {
|
|
if (days <= 0) {
|
|
System.out.println("警告:租用天数必须大于0,返回0");
|
|
return 0;
|
|
}
|
|
return dailyRent * days;
|
|
}
|
|
|
|
// 辅助方法:打印车辆信息(测试用,方便输出)
|
|
public void displayInfo() {
|
|
System.out.printf("车牌号:%s | 品牌:%s | 型号:%s | 日租金:%.2f元/天 | 状态:%s%n",
|
|
licensePlate, brand, model, dailyRent, isRented ? "已出租" : "未出租");
|
|
}
|
|
}
|