Choosing between constructor and setter methods
While the use of constructor helps in initializing the member variables during object creation. The setter methods help to assign values to member variables after the object has been created in the memory. The choice of constructor or setter methods for initializing the member variables depends upon the requirement.
Some of the examples where using a constructor which accepts arguments and then uses these arguments for initializing a member variables are:
- When no setter method has been exposed, the constructor can be used to initialize any private member variable. We can see this approach being used by the string class in JDK where in the constructor accepts a string literal object and use the characters of this literal to initialize the internal character array.
- When invoking the methods on constructor from super class is a requirement before object can be constructed, one has to resort to using constructors for member variable initialization.
- Another common scenario we constructors are used for initializing instance variable is is when those instance variables are quite significant for the object being constructed. For example when creating a Book class instance, passing the title of the book as an argument to the Book class constructor.
Using Setter Methods
Some of the examples where using the setter methods for setting instance variables are:
- When a large number of member variables are present in a class then using a constructor with say 15 arguments does not make sense and one should resort to using setter methods for initializing those 15 member variables.
- When the member variables have the property of changing their value quite frequently than one must be using the setter methods.
- The use of setter methods makes it clear as to which member variable is being set. This is because of the fact that proper naming convention is used for the names of setter methods whereas in case of constructor there is no clear indication about the arguments which need to be passed to the constructor.
One last point I want to make above the choice of using constructor or setter methods is that while one can overload the constructors to accept a different type and number of arguments which can be convenient in some cases. But that is not possible with the use of setter methods.