2012-02-29 71 views
1

是否有可能從同一個類的另一個構造函數中調用構造方法的結果?構造函數鏈中的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

+0

我不建議在構造函數中調用方法;對象構建應該是快速和簡單的。也許包含一個'init()'方法? – mre 2012-02-29 19:38:32

回答

4

你只需要使convertToInt靜態。由於它並不真正依賴於類實例中的任何內容,因此它可能並不屬於這個類。

下面是一個例子:

class MyClass { 
    public MyClass(String string) { 
     this(ComplicatedTypeConverter.fromString(string)); 
    } 

    public MyClass(ComplicatedType myType) { 
     this.myType = myType; 
    } 
} 

class ComplicatedTypeConverter { 
    public static ComplicatedType fromString(String string) { 
     return something; 
    } 
} 

你必須這樣做,這樣一來,因爲在幕後,需要的是運行自己的構造函數之前被稱爲超級構造函數(在這種情況下,對象)。通過參考this(通過方法調用)之前,發生了對​​的無形呼叫,您違反了語言約束。

參見the JLS第8.8.7和more of the JLS第12.5節。

+0

謝謝!我意識到,就像我發佈這個問題一樣,所以我認爲我會繼續,並自己回答。我不只是複製你的答案,誠實! – DenverCoder8 2012-02-29 19:32:57

+0

呵呵 - 沒問題。 :) – alpian 2012-02-29 19:36:25

+0

這是我的代碼的簡化版本,沒有用於我需要做的轉換的庫函數。 – DenverCoder8 2012-02-29 19:37:16

2

無法調用方法convertToInt,因爲它需要由對象運行,而不僅僅是來自類。因此,將代碼更改爲

public static int convertToInt(String aString) 
{ 
    return anInt; 
} 

表示構造函數完成之前的convertToInt

0

沒有它不可能。要調用實例方法,你所有的超類構造函數都必須被調用。在這種情況下,您正在調用this()來替換對super()的調用。你不能同時使用super()和this()。所以超類實例在你的情況下沒有初始化,因此你得到這個錯誤。

你可以這樣調用

public MyClass(String stringInput) { 
    super(); // No need to even call... added just for clarification 
    int i = convertToInt(stringInput); 
} 

製作方法靜電可能會解決你的問題。

+0

從構造函數中調用另一個構造函數是完全正確的。請參閱[我如何從Java中調用另一個構造函數?](http://stackoverflow.com/questions/285177/how-do-i-call-one-constructor-from-another-in-java) – 2012-02-29 20:04:18

+0

我從來沒有說你不能調用其他的構造函數。它非常好。我說過你不能在同一個構造函數中同時調用this()和super()。 – JProgrammer 2012-02-29 20:15:39

+0

這很混亂。我不認爲他問這樣的問題。 – 2012-02-29 21:06:28