Shree Naath Shree Naath - 1 year ago 59
Java Question

What is the difference between using the constructor and using getters and setters?[got the answer]

Using a constructor :

Person(String name) { = name;

Using getters and setters :

void setName(String name){;
String getName(){

Please do include all the differences if possible. And suggest me which is better..

Answer Source

Immutability makes the code better (thread-safe, more readable, safer in general) and setters are inherently the contrary of immutability.

I don't like setters, it makes things much more complicated because the value of the field is difficult to determine in certain code paths where the object is passed around in many places. It's much better practice to set all attributes to final when possible.

Rule of thumb:

  • make all fields final by default (therefore, no setter)
  • if one field absolutely cannot be final, then only make it non-final
  • if the same field absolutely must be modified from outside, then only add a setter

If you apply that rule, believe me that you will end up using practically no non-final fields and even less setters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download