2009-02-10 149 views
0

我可以使用Java初始化實例變量,當我聲明它時初始化該實例變量,並使用稍後在類中定義的方法的返回值對其進行初始化。使用類中的方法初始化實例變量

事情是這樣的:

public class MyClass { 

    integers[] myArray = new integers[length()]; 

    int length() { 
    .... 

    } 
} 

length()給了我一些數字,我想這個數字,以確定數組中元素的個數。這似乎對我來說似乎合理,但我得到NullPointerException(我不知道這個錯誤初始化是否導致異常,但我不知道究竟是什麼,並且因爲我以前從未做過這種初始化,我不確定它是正確)。

回答

-3

你必須做的方法靜態:

static int length() { … } 
3

似乎爲我工作的罰款,該方法靜態或不是靜態的:哪個生產

public class test 
{ 
    public int[] myarray = new int[this.length()]; 

    public int length() { 
     return 5; 
    } 

    public static void main(String[] args) 
    { 
     test foo = new test(); 
     for (int element : foo.myarray) { 
      System.out.println(element); 
     } 
    } 
} 

0 
0 
0 
0 
0 
+0

聽起來像是一筆交易。 :) – 2009-02-10 08:15:03

2

在做這件事之前,可能值得考慮一下,如果這個語法可能有點混亂,並且它可能更適合e在構造函數或初始化塊中初始化數組。

private final int[] myArray; 

public MyClass() { 
    myArray = new int[length()]; 
} 

private final int[] myArray; 
{ 
    myArray = new int[length()]; 
} 
2

機會是問題是某處length()方法。我懷疑它是指一個尚未適當初始化的變量。下面是這表明程序的例子:

public class MyClass { 

    int[] myArray = new int[length()]; 

    // This is only initialized *after* myArray 
    String myString = "Hi"; 

    int length() { 
     return myString.length(); 
    } 

    public static void main(String[] args) { 
     new MyClass(); // Bang! 
    } 
} 

如果這個問題,我建議你在構造函數中的初始化,而不是 - 這樣的順序是非常清晰的。

+0

+1。這個問題在有效的java http://java.sun.com/docs/books/effective/中進行了廣泛的討論。 – Chii 2009-02-11 12:50:39