我在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;
}
Run Code Online (Sandbox Code Playgroud)