I have an issue with returning and replacing the value null
with something with meaning from another class using getters and setters and would like to know what I have done incorrectly.
Configuration for getters and setters:
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");
}
}
}
Execution script for above:
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());
}
}
Any assistance into understand what I have done incorrectly would be most appreciated.
When the following code is executed:
CarClassTwo bmw = new CarClassTwo();
bmw.setMake();
at that time the values of
private String make;
private String model;
are initialized to null by default.
So when bmw.setMake();
is executed, it executes if (make.isEmpty()){
which is something like null.isEmpty() --> which will throw NullPointerException.