I know that one of the reasons for using setters and getters in Java is to validate a property. However, I was wondering how it works when we have a constructor in our class with parameters and we still can assign a wrong value using the constructor.
For instance:
public class Person() {
private String firstName;
private int age;
public Person() {}
public Person(String firstName, int age) {
this.firstName = firstName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0 && age < 100) {
this.age = age;
}else{
//throw exception
}
}
}
And the Main Class :
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.setFirstName("John");
person1.setAge(150);
Person person2 = new Person("John", 200);
}
}
In the first case (person1
) we have validation, however when using the constructor with parameters we haven't got validation, so where is the advantage when we still can set up the wrong age?
You can still invoke your setter method inside the constructor and perform the validation. That would prevent the object to be instantiated with the wrong age value anyway. Here is an example:
class Person {
private String firstName;
private int age;
public Person() {
}
public Person(String firstName, int age) throws Exception {
this.firstName = firstName;
setAge(age);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) throws Exception {
if (age > 0 && age < 100) {
this.age = age;
} else {
throw new Exception("Age " + age + " not allowed");
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
Person person2 = new Person("John", 200);
}
}
The output is:
Exception in thread "main" java.lang.Exception: Age 200 not allowed
at Person.setAge(Main.java:29)
at Person.<init>(Main.java:10)
at Main.main(Main.java:36)