Skip to content
Advertisement

Setter methods or constructors

so far I have seen two approaches of setting a variable’s value in Java. Sometimes a constructor with arguments is used, others setter methods are used to set the value of each variable.

I know that a constructor initialises an instance variable inside a class once a class is instantiated using the “new” Keyword.

But when do we use constructors and when do we use setters?

Advertisement

Answer

You should use the constructor approach, when you want to create a new instance of the object, with the values already populated(a ready to use object with value populated). This way you need not explicitly call the setter methods for each field in the object to populate them.

You set the value using a setter approach, when you want to change the value of a field, after the object has been created.

For example:-

MyObject obj1 = new MyObject("setSomeStringInMyObject"); // Constructor approach
// Yippy, I can just use my obj1, as the values are already populated
// But even after this I can change the value
obj1.setSomeString("IWantANewValue"); // Value changed using setter, if required.
..
MyObject obj2 = new MyObject();
obj2.setSomeString("setSomeStringNow"); // Setter approach
// values weren't populated - I had to do that. Sad :(

And as Axel mentioned, if you want to create immutable objects, you cannot use setter-methods approach. I won’t say everything has to be initialised in the constructor because different approaches exist, like lazy-evaluation which can be used even with immutable objects.

User contributions licensed under: CC BY-SA
11 People found this is helpful
Advertisement