I was doing a project in a Java book and came across this code example. The author of the book said that instead of initializing X and Y in my constructor directly, I could call the class’s setLocation() method instead. Unfortunately I do not have the book anymore for a concrete explanation on why this is better. I’m not too experienced with Java but isn’t it just…simpler to assign values directly and not worry about another function call?
//Point constructor, normal way of initializing variables
private double x;
private double y;
Point(double initial_x, double initial_y)
{
this.x = initial_x;
this.y = initial_y;
}
//Point constructor, the other way
Point(double initial_x, double initial_y)
{
setLocation(initial_x, initial_y);
}
public void setLocation(double newX, double newY)
{
this.x = newX;
this.y = newY;
}
I would actually recommend against calling setters within a constructor, because calling overridable methods from within constructors is a bad idea. Also, the usual argument for getters/setters is that the logic may change, and you won’t have to change everyone that accesses your properties. In this case, however, if the logic changes, the necessary changes are limited to the same class.