我想了解Java构造函数super()
。让我们来看看以下课程:了解Java超级()构造函数
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0, 0);
}
}
该课程将编译。如果我们创建一个新的Point
对象说Point a = new Point();
没有参数的构造函数将被调用:Point()
。
纠正我,如果我错了,在做this(0,0)
之前,Class
构造函数将被调用,只有Point(0,0)
将被调用。 如果这是真的,说默认调用super()
是否正确?
现在,让我们看看相同的代码与一个小的变化:现在
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
super(); // this is the change.
this(0, 0);
}
}
,代码将无法编译,因为this(0,0)
不在构造函数的第一线。这是我感到困惑的地方。为什么代码不能编译?无论如何都不会调用super()
? (如上所述的类构造函数)。
点不是子类。想象一下,如果我们有一个子类PrettyPoint,那么PrettyPoint(){super(0,0); }会从上面调用Point(int x,int y)。 – ZeldaZach
这将帮助你理解:https://stackoverflow.com/questions/10381244/why-cant-this-and-super-both-be-used-together-in-a-constructor –
@ZeldaZach一切都是一个子类'对象'。 –