Togusa Togusa - 2 months ago 12
Java Question

When to use Setters, and when to use Constructors to set variable values?

I see we can encapsulate instance variables with setters, however, Constructors seem to do the same thing.

Class object1 = new Class(100, 100) // setting using Constructor

object1.setValue(100, 100) // setting using Setters


When should I use setters, and when should I use Constructors to initialize instance variable values?

Answer

Use the constructor when the value is required for the object to make sense, or when you need to provide multiple values at once for consistency or convenience; for example, a Rectangle must have a length and a width.

Rectangle r = new Rectangle(10, 20);

Provide setters when you have optional values (such as a color) or values that can be changed after the object is created:

r.setColor(Color.BLUE);

Note that it's usually preferable to create immutable "value objects" whenever possible, since these eliminate several types of potential bugs. Value objects must be initialized all at once, though they frequently also have methods that return a new, similar object:

r = r.withLength(15);
Comments