我以前从未需要这样做,但由于两者都必须是构造函数中的"第一行",应该如何解决它?对于这样的情况,最好的重构是什么?
这是一个示例:
public class Agreement extends Postable {
public Agreement(User user, Data dataCovered)
{
super(user);
this(user,dataCovered,null);
}
public Agreement(User user,Data dataCovered, Price price)
{
super(user);
if(price!=null)
this.price = price;
this.dataCovered = dataCovered;
}
...
}
Run Code Online (Sandbox Code Playgroud)
呼吁super(user)是绝对必须的.在这种情况下如何处理"可选参数"?我能想到的唯一方法就是重复,即根本不要称之为(...).只需在每个构造函数中执行赋值.
我正在尝试理解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);
}
}
Run Code Online (Sandbox Code Playgroud)
这个类将编译.如果我们创建一个新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. …Run Code Online (Sandbox Code Playgroud)