我在使用getter和setters返回并替换值null
到另一个类中的含义时遇到了问题,想知道我做错了什么。
获取器和设置器的配置:
public class CarClass {
private String make;
private String model;
private int yearOfMake;
public void setMake(String make){
if (make.isEmpty()){
this.make = "";
System.out.println("Error please input value");
} else {
System.out.println("Hello");
this.make = make;
}
}
public String getMake(){
return make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
if (model.isEmpty()){
this.model = "";
System.out.println("Error, you have not entered a valid model");
} else {
this.model = model;
}
}
public int getYearOfMake() {
return yearOfMake;
}
public void setYearOfMake(int yearOfMake) {
if (yearOfMake > 1900)
this.yearOfMake = yearOfMake;
else {
this.yearOfMake = yearOfMake;
System.out.println("Year of make is invalid");
}
}
}
以上执行脚本:
public class GetterSetter {
public static void main(String[] args) {
CarClassTwo bmw = new CarClassTwo();
bmw.setMake();
System.out.println(bmw.getMake());
CarClass benz = new CarClass();
benz.setModel("C300");
System.out.println(benz.getModel());
benz.setYearOfMake(1999);
System.out.println(benz.getYearOfMake());
System.out.println("!!!!!!!!");
benz.setModel("C300");
System.out.println(benz.getModel());
benz.setYearOfMake(1800);
System.out.println(benz.getYearOfMake());
System.out.println(bmw.getMake());
System.out.println(bmw.getModel());
}
}
对理解我的不正确做法提供的任何帮助,将不胜感激。
执行以下代码时:
CarClassTwo bmw = new CarClassTwo();
bmw.setMake();
当时的值
private String make;
private String model;
默认情况下初始化为null。
因此,当执行bmw.setMake();
时,它将执行if (make.isEmpty()){
类似于null.isEmpty()->会抛出NullPointerException。