Reputation: 53
There's something I'm missing here. with this code I get a java.lang.NullPointerException
:
public static void main(String[] args) {
Board board = new Board();
board.Initialise();
}
public class Board {
private Obj[][] tableau;
public void Board() {
tableau = new Obj[8][8];
}
public void Fill_Board() {
tableau[0][0]= new Obj('B');
}
}
But with this other code I get no error. What I am doing wrong, and how to initialize properly this array of object?
public class Board {
private Obj[][] tableau = new Obj[8][8];
public void Board() {
}
public void Fill_Board() {
tableau[0][0]= new Obj('B');
}
}
Upvotes: 0
Views: 600
Reputation: 500257
Board()
ends up being a member function and not a constructor, and therefore never gets called. The problem is the void
keyword, which needs to be removed:
public Board() { /* removed the `void' */
tableau = new Obj[8][8];
}
Upvotes: 2
Reputation: 663
I get no error when I run this code (changing Obj to an actual class), perhaps you can provide a more concrete example with a main method of what you're trying to do?
If you're looking at making a constructor then it needs to be the same name as your class, i.e. Tab
and have no return type.
So you would need to add:
public Tab() {
// initialization code here
}
You're constructor will run whenever you create a new instance of that class. You want to use it to initialize all of your variables.
Tab t = new Tab(); // Constructor runs
Edit:
You're main method uses class Board
but you have given us a class called Tab
. I can assume that you really want class Board so you should change all Tab
to Board
in the above example, if that's what you're looking for.
Upvotes: 0