0

Can I initialize an instance variable in Java, when I initialise it when I declare it, and initialise it with the return value of a method, which I define later in the class.

Something like this:

public class MyClass {

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

     int length() {
     ....

     }
}

length() gives me some number, and I want this number to determine the number of elements in the array. It seems plausible to me, but I get NullPointerException (I don't know whether this mistake initialization is causing the exception, but I don't know what exactly, and because I have never done this initialization before, I am not sure it is correct).

4

4 に答える 4

3

Seems to work fine for me, with the method static or not static:

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);
        }
    }
}

Which produces:

0
0
0
0
0
于 2009-02-10T07:52:03.597 に答える
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!
    }
}

これ問題である場合は、代わりにコンストラクター内で初期化を行うことをお勧めします。そうすれば、順序がはるかに明確になります。

于 2009-02-10T08:37:37.763 に答える
2

これを行う前に、この構文が少し混乱する可能性があるかどうか、およびコンストラクターまたは初期化ブロックで配列を初期化する方が適切であるかどうかを検討する価値があるかもしれません。

private final int[] myArray;

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

また

private final int[] myArray;
{
    myArray = new int[length()];
}
于 2009-02-10T07:54:38.117 に答える
-3

You have to make the method static:

static int length() { … }
于 2009-02-10T07:49:56.083 に答える