运维开发网

Java 如何初始化类的对象?

运维开发网 https://www.qedev.com 2020-03-17 10:46 出处:网络 作者:运维开发网整理
我的代码是这样的: 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
我的代码是这样的:

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

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

Exception in thread "Foo" java.lang.NullPointerException

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消