我有以下课程:
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); } }该类包含两个可选值,我想提供所有可能的构造函数排列。第一个版本没有初始化任何东西,第二个版本只初始化第一个值,第三个版本只初始化第二个值。
The class contains two optional values and I would like to provide all possible constructor permutations. The first version does not initialize anything, the second initializes only the first value and the third initializes only the second value.
最后一个构造函数是第二个和第三个的组合一。但是不可能把它写下来,因为代码失败了。
The last constructor is the combination of the second and third one. But it is not possible to write this down, because the code fails with.
constructor.java:13: call to this must be first statement in constructor this(cdr); ^ 1 error是否可以编写最后一个没有任何代码冗余的构造函数(也可以不调用相同的setter方法)?
Is it possible to write the last constructor without any code redundancy (also without calling the same setter methods)?
推荐答案通常,参数较少的构造函数应该调用那些具有更多参数的构造函数。
As a rule, constructors with fewer arguments should call those with more.
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; }更多推荐
如何避免Java中的构造函数代码冗余?
发布评论