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


I met such a construction in the 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 the constructor is also capable of. Why use a constructor that uses a setter that will assign a value to a variable if you can get by with a constructor? There are cases when this is necessary, or is it just a theoretical example that this is possible?

Author: dirkgntly, 2016-06-27

2 answers

The setter does not always just assign a value to a variable, most often it still performs some actions(normalizes data, for example), so in order not to duplicate the code from the setter in the constructor, you can simply call the setter from the constructor.

 10
Author: Aim X, 2016-06-27 21:30:38

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

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

Class constructors must not call overridable methods, directly or indirectly. Violation of this rule may result in cause the program to crash. Superclass Constructor it is executed before the subclass constructor, so the overriding method in the subclass will be called before the subclass constructor is run. And if the overridden method depends on the initialization that the subclass constructor performs, then this method will not work at all as expected

 12
Author: Mikhail Chibel, 2016-06-28 00:49:16