简体   繁体   中英

How do I correctly instantiate a public class+data structure in a class so that other objects can use it?

In my code, I have a seperate Runner class that instantiates a World, which has a 4x4 array of Locations (a separate class) stored as a Location[][] array. When I print/try to use the Location array, its value is null, and it throws a NullPointerException.

public class Runner 
{
public static void main(String[] args)
{
...
WumpusWorld test_loc = new WumpusWorld();
System.out.print(test_loc) //This prints an ID for the WumpusWorld object
System.out.print(test_loc.world) //Null value prints here
//I'd like to pass the test_loc.world values to an actor here
...
}
}

The applicable code for the WumpusWorld is as follows:

public class WumpusWorld 
{
public Location[][] world;
public WumpusWorld()
{
    new WumpusWorld((byte) 4); //this constructor is used
}
...
public WumpusWorld(byte size)
{
this.world = new Location[size][size];
for(byte i = 0; i<size; i++)
{
    for(byte j = 0;j<size;j++)
    {
    world[i][j] = new Location(j,i,true,false,false);
    }
    //Location instances called in the form world[x][y]
    //are error free in constructor
...
}
}

Your problem might be in the way you call public WumpusWorld(byte size) from the default constructor.

Try this:

public WumpusWorld()
{
    this((byte) 4);
}

With new in the call, I had uninitialized values in the inner class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM