I have a (rather static) class like:
class Test
{
private Planet gault;
private Planet irtok;
private Planet ktaris;
/* problem:
private Planet [] planets = {
this.gault, this.irtok, this.ktaris
};
*/
Test() {
}
public void doTest() {
this.gault = new Planet("Klingon", 1322);
this.irtok = new Planet("Ferengi", 1213);
this.ktaris = new Planet("Ktarian", 16512);
}
}
What I want (if I can) is to have an array pointing to each planet – .
private Planet [] planets = {
this.gault, this.irtok, this.ktaris
};
So that I in doTest() can do something like:
for (Planet p: in planets)
p.printInfo();
From the various ways I’ve tried I always end up with p being NULL;
Your planets are null by default. You only initialize them in the
doTest()method. But the line initializing the array of planets is executed long before: when the Test object is constructed. So at this time, all the planets are still null, sincedoTest()has not been called yet.The array should be initialized right after the planets are. And everything should probablybe done in the constructor rather than in
doTest().