Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a set Method inside a Constructor

I have a number of set methods setup and using a constructor to initiate their value as follows. It is working but I am concerned as to whether it is a normal Java convention to do so (is it normal to call a set method inside a constructor?).

The alternative way I can think of is to call an empty constructor and call the set methods one by one in the main method to set the value. I find this second method tedious. Please advice if what I have done is fine/ within Java convention or if there is a better way to do it. Do tell if I need to post more code to make my question more clearer. I can post it all if it would make better sense. Thank you.

public Person(String foreName,String surName, int age, double height, String gender){
        personCount++; 
        setForeName(foreName);
        setSurName(surName);
        setAge(age);
        setHeight(height);
        setGender(gender); 
    }
like image 559
kar Avatar asked Dec 04 '22 07:12

kar


1 Answers

If using this doesn't bypass the validation rules defined in the setters, it's just a matter of taste:

public Person(String foreName,String surName, int age, double height, String gender){
    personCount++; 
    this.foreName = foreName;
    //same goes for the rest of the params
}
like image 139
Konstantin Yovkov Avatar answered Dec 06 '22 21:12

Konstantin Yovkov