如何初始化类的对象?

wro*_*ame 3 java null initialization nullpointerexception

我的代码是这样的:

public class Foo {
    public int a;
    Bar[] bar = new Bar[10];

    a = bar[0].baz;
}

public class Bar {
    public int b;

    public Bar () { //I tried doing away with this constructor, but that didn't
                    //fix anything
        b = 0;
    }

    public int Baz () {
        //do somthing
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到类似于的错误消息:

Exception in thread "Foo" java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)

在Foo中的哪一行,我尝试调用类Bar的任何函数或值.如何防止bar []为空?

编辑:经过一番摆弄,我终于把它修好了,谢谢大家!但是,我无法调用构造函数来解决问题; 我必须创建另一个函数并从Main调用该函数(在我的例子中,类Foo实际上是Main类,如果真的很重要).我的最终结果:

public class Foo {
    public int a;
    Bar[] bar = new Bar[10];

    public Foo () { //this constructor wasn't called for some reason... I checked this
                    //by using System.out.println... no message was print onscreen
        for (int a = 0; a < bar.length; a++)
            bar[a] = new Bar();
    }

    public static void initializeFoo () {
        for (int a = 0; a < bar.length; a++)
            bar[a] = new Bar();
    }

    public static void Foo () {
        initializeFoo();
        a = bar[0].baz;
    }
}
Run Code Online (Sandbox Code Playgroud)

有人想帮我解决这个问题,还是我想创造另一个问题?:)

Mic*_*rdt 8

Bar[] bar = new Bar[10];

a = bar[0].baz;
Run Code Online (Sandbox Code Playgroud)

上面创建了一个Bar类型的数组,但不会用任何实际的Bar对象填充它.使用空引用初始化引用类型的数组.你需要这样做:

for(int i=0; i<bar.length; i++) {
    bar[i] = new Bar();
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*rav 6

你已经通过编写这个来为引用分配内存,Bar[] bar = new Bar[10];但谁将为数组元素分配内存?实际的引用类型数组使用空引用进行初始化.

您还需要为数组元素分配内存:

for(int i=0; i<bar.length; ++i)
   bar[i]=new Bar();
Run Code Online (Sandbox Code Playgroud)