I am very much confused about the setter method and the constructor in a class. My question is when you can set value using setter method then why use constructor to set value when both does the same function.
You may use the constructor to set values at point of instantiation. However, an object may have many attributes that 1) you may not know at the point of instantiating or 2) may need to be changed after instantiating.
For this you need setters.
Calling the setters in the code creation is different to having setters in the class or not,
For having cleaner and smaller code its better not to have setters in the class and set the value directly in the constructor and only introduce the setter if there is a need for it, if you dont need to have a setter than why have more code than what is needed :)
The important thing about constructors are:
- They have to be called when creating an object
- They are only called once per object.
So you should definitely use a constructor if:
- A value has to be provided. You can't force someone to call a setter, but with a constructor you can force someone to pass a suitable value in.
- A value should be provided once and then never changed. For example, if you're writing an immutable class. In this case you'll have a constructor but no setter.
Vignesh Jeffry wrote:My question is when you can set value using setter method then why use constructor to set value when both does the same function.
You might do better to turn the question around and ask: if you can set a value in a constructor, why do you need a setter?
And the answer is: to change a value - and the need for that is not as great as you might think.
Providing public setters makes a class mutable, and that's not always a good thing; so my advice would be to resist the temptation to provide setter methods unless you're absolutely sure you need them.
Isn't it funny how there's always time and money enough to do it WRONG?
Joined: Apr 27, 2012
Thanks all. By the way i came to know that the prime difference is setter methods can handle user exceptions. Is it that true?
Vignesh Jeffry wrote:Thanks all. By the way i came to know that the prime difference is setter methods can handle user exceptions. Is it that true?
It's certainly not the prime difference. Whether it's a difference at all depends on what you mean by that. But the prime difference is that a setter allows the value to be changed after it was initialised.