我有以下類:如何避免Java中的構造器代碼冗餘?
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方法)?
你和this()和super()的問題必須是[構造函數中的第一個語句] [1]。 [1]:http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor – iMBMT
您可以調用這個(...)構造函數兩次,只能有一個構造函數調用另一個構造函數,並且鏈接的構造函數調用必須是構造函數中的第一個語句。 – RudolphEst