Alex Watson
Alex Watson

Reputation: 77

Unkown Class error when trying to create a new object

I have a class named Tile of which I want to create a double array named grid. The strange part is when I do this

private final int size = 5;
public Tile[][] grid = new Tile[size][size];

it doesn't show any error, but when I try to access grid it throws a null pointer exception. So I tried this

private final int size = 5;
public Tile[][] grid;
grid = new Tile[size][size];

now it immediately underlines it in read with the error "Unknown class: 'grid'".

Here are the two classes Grid:

public class Grid {

    public Grid(String[][] grid){
        initiateGrid(grid);
    }

    private final int size = 5;
    public Tile[][] grid ; grid = new Tile[size][size];

    public void initiateGrid(String[][] grid){
        for(int i=0; i<5; i++){
            for(int j=0; j<5; j++){
                this.grid[i][j].setContent(grid[i][j]);
            }
        }
    }
    public void crossTile(Tile tile){
        tile.valid = false;
    }
}

Tile:

public class Tile {
    public Tile(){
        this.content = "";
        this.active = false;
        this.valid = true;
    }

    public String content;
    public boolean active;
    public boolean valid;

    public void setContent(String content){
        this.content = content;
    }

}

Any tips what I am missing here?

Upvotes: 0

Views: 42

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103073

grid = new Tile[size][size]; is a statement, and not a field declaration.

Statements cannot occur in classes; they can only occur in constructors, initializer blocks, and methods.

Thus, your alternative attempt is straight up invalid java.

The problem is:

new Tile[size][size] makes a new 2Dish array that can hold Tile objects, but none of the 'slots' are initialized. You'd have to loop through the x and y coords and create a new Tile object.

You want size x size Tile objects, clearly. That means new Tile() needs to be invoked somewhere in your code, and size x size times. Go back to your original, then add that loop to make tiles.

Upvotes: 3

Related Questions