Why use setters in java instead of constructors? [duplicate]

Because you can change the value later for the same instance. For example, let’s assume a person with the following class:

public class Person {
  String firstName;
  String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
}

Imagine there is a woman named “Linda Croft” which is now single.

Person linda = new Person("Linda", "Croft");

Then, after a couple of years, he marry a man named “John Wick”. Then “Linda” want to change her name to his husband name after marriage. If we don’t have a setter, we need to create another “Linda”, which is obviously another person:

Person anotherLinda = new Person("Linda", "Wick");

with the setter, we can update her name with:

linda.setLastName("Wick");

Now Linda name is “Linda Wick”.

Leave a Comment