Setters serve only a single function of constructors in java i.e assigning value to instance variables. Why do we need them? Can you explain with an example? I understand the question I asked was rudimentary and I am sorry for that. I am new to programming and as soon as I found stackoverflow, I asked this question which has been bugging me for quite a time. I tried deleting, but that was not allowed.
Asked
Active
Viewed 892 times
-6
-
2Setters allow you to mutate the state of an object after initialization. On the other hand, a constructor can only set state once. – Tim Biegeleisen Dec 04 '17 at 09:38
-
Because obviously you sometimes want to change values in an already existing object. Only allowing setting values in constructor would make every object immutable. – OH GOD SPIDERS Dec 04 '17 at 09:38
-
Is it possible that you don't mean constructors by saying constructors? Is it possible you mean setting values of non-private fields? – Clijsters Dec 04 '17 at 09:45
1 Answers
2
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".

ישו אוהב אותך
- 28,609
- 11
- 78
- 96