你好,我仍然是java的新手.当涉及到实例变量时,我得到了"this"的概念,但是当我在没有参数的构造函数中使用它时,我会有点困惑.所以我的问题是这样的工作怎么样?
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
public Point(double x, double y){
this.x=x;
this.y=y; // Done sets the x,y private types to the x,y type provided in the ()
}
public Point(){
this(0.0,0.0); //Sets, x and y to doubles of 0.0,0.0??
} //How does this work?
Run Code Online (Sandbox Code Playgroud)
我的point()构造函数会通过调用point(x,y)构造函数来创建(0.0,0.0)的原点吗?任何有关这方面的澄清都会对我有所帮助!
this(arguments)
是一种只在构造函数中可用的特殊语法.它的作用是使用给定的参数调用另一个构造函数.所以调用this(0.0, 0.0)
将Point(double, double)
使用值调用构造函数(0.0, 0.0)
.这反过来,将设置x
和y
到0.0
.
调用时this()
,您将该构造函数的调用重定向到另一个构造函数(在本例中为第一个构造函数)。所以你创建了一个Point
(0,0)。
您基本上指出,每当有人调用时new Point()
,它都会被 Java 替换为new Point(0.0,0.0)
有时,做相反的事情可能很有用(调用带有较少参数的构造函数)。在这种情况下,每个构造函数只处理其附加参数,这更面向“关注点分离”。
例如:
public class Point {
private double x = 0.0d;
private double y = 0.0d;
public Point () {
}
public Point (double x) {
this();
this.x = x;
}
public Point (double x, double y) {
this(x);
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)