0
Why use a Setter while you can use a constructor.?
A constructor is easier to set that repeating the code in a Setter. Is there where you can use a Setter only, where you can't use a constructor?
3 Answers
+ 6
A constructor creates a new object. Every time when you want to change a value you need to create a new object.
A setter is for changing variables of already created objects.
+ 4
They serve different purposes.
A Constructor is a method used to initialize an object of a class with certain attributes which you can pass as arguments.
On the other hand, a Setter is a method used to set the value of some attribute after the object is already created. Also, Setters are specially useful to alter private attributes, since you can't manipulate them directly.
+ 2
What if you need to change or set a private variable in a class for multiple times, will you kept on changing them with constructors and get memory(heap) leak?
Or instead setters?
Now you can relate! :)