我的代码是这样的:如何初始化一个类的对象?
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
在富哪个行我尝试调用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;
}
}
任何人都想帮助我,或者我应该创建另一个问题? :)
你总是做同样的方式 - 初始化它指向堆中的对象。 – duffymo 2010-01-24 16:12:42
如果你需要帮助你的代码,你将不得不向我们展示实际导致问题的代码,而不是你认为代表问题的其他代码,但错过了重要的位,甚至没有编译。 – 2010-01-24 16:57:40
@Michael谢谢,下次我会这样做 – wrongusername 2010-01-25 01:05:40