是否有可能從同一個類的另一個構造函數中調用構造方法的結果?構造函數鏈中的Java方法調用
我希望能夠接受多種形式的輸入,並有類似:
public class MyClass
{
public MyClass(int intInput)
{
...
}
public MyClass(String stringInput);
{
this(convertToInt(stringInput));
}
public int convertToInt(String aString)
{
return anInt;
}
}
當我嘗試編譯,我得到
error: cannot reference this before supertype constructor has been called
指的convertToInt
。
我不建議在構造函數中調用方法;對象構建應該是快速和簡單的。也許包含一個'init()'方法? – mre 2012-02-29 19:38:32