我在一本 Java 书籍中做一个项目,并遇到了这个代码示例。这本书的作者说,与其直接在我的构造函数中初始化 X 和 Y,我可以调用类的 setLocation() 方法来代替。不幸的是,我不再有这本书来具体解释为什么这会更好。我对 Java 的经验不是很丰富,但它不只是......更简单地直接分配值而不用担心另一个函数调用吗?
//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;
}