When learning Java constructor and mutator, I found out that setter can be used to perform validation. But if we directly use constructor to create a new instance, wouldn't it bypass the validation in setter? Below is the sample code:
public static void main(String[] args){
Person p1 = new Person("My Name", "My Gender"); //bypass setter validation
p1.setGender("Female"); //validation is performed
}
public class Person{
public Person(String name, String gender){
this.name = name;
this.gender = gender;
}
public void setGender(String gender){
if(gender.equals("Male") || gender.equals("Female")){
this.gender = gender;
}
else{
this.gender = "undefined";
}
}
}
I have seen some mentioned that you can call the setter in the constructor, but seems like it is not a good approach as a lot of forums mentioned that it will cause some "overridden" issue. If that's the case, is there anything I can do to make sure that the setter validation can be performed when I'm calling my constructor?
Thanks in advance!