我试图理解Java super()
构造函数。我们来看看下面的课程:
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()
召唤? (如上所述的类构造函数)。
答案 0 :(得分:5)
this(0, 0);
将调用同一个类的构造函数,super()
将调用Point
类的超级/父类。
现在,代码不会编译,因为这(0,0)不在第一行 构造函数。这是我感到困惑的地方。为什么代码赢了 编译?无论如何都不会调用super()吗?
super()
必须是构造函数的第一行,this()
必须是构造函数中的第一行。所以两者都不能在第一行(不可能),这意味着,我们不能在构造函数中添加两者。
作为关于您的代码的说明:
this(0, 0);
将调用带有两个参数(在Point
类中)的构造函数,并且两个参数构造函数将隐式调用super()
(因为您没有明确地调用它)。
答案 1 :(得分:4)
将super()放在第一个构造函数中,它应该可以工作。
var values = new[] { newitems, childs}
var body= new FormUrlEncodedContent(values);

答案 2 :(得分:4)
您可以从同一构造函数中调用this()
或 super()
,但不能同时调用两者。当您致电this()
时,会自动从其他构造函数(您使用super()
调用的构造函数)调用this()
。
答案 3 :(得分:1)
通过调用this(...)
,您将被强制调用您在那里调用的构造函数中的超级构造函数(如果存在)。
调用this(...)
或super(...)
始终是您在构造函数中调用的第一种方法。
修改强>
class Point {
private int x, y;
public Point(int x, int y) {
super(...); //would work here
this.x = x;
this.y = y;
}
public Point() {
this(0, 0); //but this(...) must be first in a constructor if you want to call another constructor
}
}
答案 4 :(得分:1)
构造函数可以使用super()
方法调用来调用超类的构造函数。唯一的限制是它应该是第一个声明。
public Animal() {
super();
this.name = "Default Name";
}
此代码会编译吗?
public Animal() {
this.name = "Default Name";
super();
}
答案是否。应始终在构造函数的第一行调用super()
。