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?

2nd Dec 2019, 9:12 AM
Mwebaze Andrew
Mwebaze Andrew - avatar
3 Respuestas
+ 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.
2nd Dec 2019, 9:55 AM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
2nd Dec 2019, 9:18 AM
Eduardo Petry
Eduardo Petry - avatar
+ 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! :)
3rd Dec 2019, 8:02 AM
minirkk
minirkk - avatar