我有以下class:
class Pair
{
String car;
Integer cdr;
public Pair () {}
public Pair (String car) { this.car = car; }
public Pair (Integer cdr) { this.cdr = cdr; }
public Pair (String car, Integer cdr)
{
this(car);
this(cdr);
}
}
该类包含两个可选值,我想提供所有可能的构造函数排列。第一个版本不初始化任何东西,第二个版本只初始化第一个值,第三个版本初始化第二个值。
最后一个构造函数是第二个和第三个的组合。但是不可能写下来,因为代码失败。
constructor.java:13: call to this must be first statement in constructor
this(cdr);
^
1 error
是否有可能写没有任何代码冗余的最后一个构造函数(也没有调用相同的setter方法)?
发布于 2018-03-23 13:54:55
通常,参数较少的构造函数应该使用更多的参数。
public Pair() {}
public Pair(String car) { this(car, null); }
public Pair(Integer cdr) { this(null, cdr); }
public Pair(String car, Integer cdr) { this.car = car; this.cdr = cdr; }
https://stackoverflow.com/questions/-100007754
复制相似问题