views:

381

answers:

4

Hello,

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). Thank you.

A: 

You have to make the method static:

static int length() { … }
kmkaplan
+3  A: 

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
Chris Bunch
Sounds like a deal. :)
Chris Bunch
+2  A: 

Before doing this, it might be worth considering if this syntax might be slightly confusing, and that it might be more appropriate to initialize the array in the constructor, or in an initialization block.

private final int[] myArray;

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

or

private final int[] myArray;
{
    myArray = new int[length()];
}
David Grant
+2  A: 

Chances are the problem is somewhere in the length() method. I suspect it refers to a variable which hasn't been appropriately initialized yet. Here's an example of a program which shows that:

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!
    }
}

If this is the problem, I suggest you do the initialization within the constructor instead - that way the ordering is much clearer.

Jon Skeet
+1. this problem is discussed extensively in effective java http://java.sun.com/docs/books/effective/.
Chii