arynaq
arynaq

Reputation: 6870

How do I call a constructor?

I am currently done making a sokoban game with GUI and everything and I am working on optimzation, I would like to keep the objects as sensible as possible and therefore need to be able to call the constructor from a method in the class/object. Suppose:

public class BoardGame() {

public BoardGame)() {
this(1)
}

public BoardGame(int level){
//Do stuff, like calling filelevel-to-board loaderclass
}

How do I create a method that calls the constructor of this object/class in the object/class itself? Eg:

public BoardGame nextLevel() {
return BoardGame(currentLevel+1);
}

The above is apparently undefined!

Such that if I want to use this object in another class I should be able to do:

GameBoard sokoban = new GameBoard(); //lvl1
draw(GameBoard);
draw(GameBoard.nextLevel()); //draws lvl2

Upvotes: 1

Views: 109

Answers (2)

Cephalopod
Cephalopod

Reputation: 15145

Calling the constructor requires the new keyword and always creates a new instance. For instance, in your example code

GameBoard sokoban = new GameBoard(); //lvl1
draw(sokoban );
draw(sokoban.nextLevel()); //draws lvl2
sokoban <-- still level 1

Maybe you want the GameBoard to be mutable:

public class GameBoard {

    public GameBoard() {
        setLevel(1);
    }

    private void setLevel(int i) {
        currentLevel = i;
        ....
    }

    public void nextLevel() {
        setLevel(currentLevel+1);
    }
}

Upvotes: 0

Alan Krueger
Alan Krueger

Reputation: 4786

You need to use the new keyword to call the constructor.

public BoardGame nextLevel() {
    return new BoardGame(currentLevel + 1);
}

Upvotes: 2

Related Questions