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.
96 lines
2.7 KiB
96 lines
2.7 KiB
public class Car {
|
|
// 1. 私有成员变量(封装核心:隐藏内部数据)
|
|
private String brand; // 品牌
|
|
private String model; // 型号
|
|
private int year; // 生产年份
|
|
private double price; // 价格
|
|
|
|
// 2. 无参构造方法(构造方法重载 1)
|
|
public Car() {
|
|
// 默认值
|
|
this.brand = "未知品牌";
|
|
this.model = "未知型号";
|
|
this.year = 2020;
|
|
this.price = 0.0;
|
|
}
|
|
|
|
// 3. 带参构造方法(构造方法重载 2:只传入品牌和型号)
|
|
public Car(String brand, String model) {
|
|
this.brand = brand;
|
|
this.model = model;
|
|
this.year = 2020; // 默认年份
|
|
this.price = 0.0; // 默认价格
|
|
}
|
|
|
|
// 4. 全参构造方法(构造方法重载 3:传入所有属性,含数据校验)
|
|
public Car(String brand, String model, int year, double price) {
|
|
this.brand = brand;
|
|
this.model = model;
|
|
// 数据校验:年份必须在 1900~2026 之间
|
|
if (year >= 1900 && year <= 2026) {
|
|
this.year = year;
|
|
} else {
|
|
System.out.println("年份输入不合法,已设置为默认值 2020");
|
|
this.year = 2020;
|
|
}
|
|
// 数据校验:价格不能为负数
|
|
if (price >= 0) {
|
|
this.price = price;
|
|
} else {
|
|
System.out.println("价格输入不合法,已设置为默认值 0.0");
|
|
this.price = 0.0;
|
|
}
|
|
}
|
|
|
|
// 5. 公共 getter/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 int getYear() {
|
|
return year;
|
|
}
|
|
|
|
public void setYear(int year) {
|
|
// 校验年份
|
|
if (year >= 1900 && year <= 2026) {
|
|
this.year = year;
|
|
} else {
|
|
System.out.println("年份输入不合法,未修改");
|
|
}
|
|
}
|
|
|
|
public double getPrice() {
|
|
return price;
|
|
}
|
|
|
|
public void setPrice(double price) {
|
|
// 校验价格
|
|
if (price >= 0) {
|
|
this.price = price;
|
|
} else {
|
|
System.out.println("价格输入不合法,未修改");
|
|
}
|
|
}
|
|
|
|
// 6. 显示车辆信息的方法
|
|
public void showInfo() {
|
|
System.out.println("=== 车辆信息 ===");
|
|
System.out.println("品牌:" + this.brand);
|
|
System.out.println("型号:" + this.model);
|
|
System.out.println("生产年份:" + this.year);
|
|
System.out.println("价格:" + this.price + " 万");
|
|
}
|
|
}
|