2013-03-27 27 views
2

我已經在下面的代碼中初始化變量如下。可以像這樣初始化嗎?以這種方式初始化非靜態成員變量會有什麼問題嗎?

public class StaticInit { 

    int x = getInt(); 
    String z = "Lucky Number " + processInt(x); 

    public static int getInt() { 
     int ret = 10; 
     System.out.println("ret- " + ret); 
     return ret; 
    } 

    public static int processInt(int toProcess) { 
     int toRet = toProcess/2; 
     System.out.println("toRet- " + toRet); 
     return toRet; 
    } 

    public static void main(String[] args) { 
     StaticInit sit = new StaticInit(); 
    } 
} 

回答

2

您可以使用變量聲明或在構造函數中進行初始化。有些人會爭辯說,其中一個或者更好,但是可以工作。我相信在構造函數中初始化的參數是所有變量初始化都在同一個地方,因爲在某些情況下,並不是所有的東西都可以在構造函數之外初始化。

public class StaticInit { 

    int x = getInt(); 
    String z = "Lucky Number " + processInt(x); 

} 

public class StaticInit { 

    int x; 
    String z; 

    public StaticInit() { 
     x = 10; 
     z = x/2; 
    } 
} 

對於這種情況,特別是雖然,我肯定會推薦使用構造,因爲z依靠x。另外構造函數比使用靜態方法好得多。

+0

在某些情況下,並非所有的東西都可以在構造函數之外初始化。 - 例子? – 2013-03-27 11:10:54

+1

如果構造函數具有將初始化變量的參數,例如。 – 2013-03-27 11:11:40

2

個人而言,我不會在getInt(),而是在構造函數中初始化它。

除非你打算在外部使用getInt()函數,否則我沒有看到它的意義,尤其是因爲它返回一個硬編碼值。

相關問題