Java. A constructor that uses a setter – when is it needed?

Question:

Met such a construction in a training example.

public class Vehicle {
  private String color;

 //Constructor
  Vehicle(String c) {
    this.setColor(c);
  }

  // Setter
  public void setColor(String c) {
    this.color = c;
  }
}

As far as I understand, the setter is used to set the value of a private variable, which is what a constructor is capable of. Why use a constructor that uses a setter that assigns a value to a variable when you can get by with a constructor? There are times when it is necessary, or is it just a theoretical example that this is possible?

Answer:

Bad teaching example. I would not recommend using setters inside a constructor, especially if the setter is simple. If the setter contains a lot of things, then in this case it is better to revise the structure of the class, perhaps it would be better to use the Builder pattern to create an instance of the class. The main problem with setters inside a constructor (more precisely, with setters that can be overridden) is that they can create a bunch of problems if the method is overridden.

Quote from the JAVA book: Effective Programming. 2nd edition, Joshua Bloch. Article 17.

Class constructors should not call overridden methods , directly or indirectly. Violation of this rule can lead to an abnormal program termination. The constructor of a superclass is executed before the constructor of the subclass, and therefore the overriding method in the subclass will be called before the constructor of that subclass is invoked. And if the overridden method depends on the initialization that the subclass constructor does, then this method will not work at all as expected.

Scroll to Top