1

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
4

2 に答える 2

2

newコンストラクターを呼び出すには、キーワードを使用する必要があります。

public BoardGame nextLevel() {
    return new BoardGame(currentLevel + 1);
}
于 2013-02-28T19:45:00.727 に答える
0

コンストラクターを呼び出すにはnewキーワードが必要であり、常に新しいインスタンスを作成します。たとえば、サンプルコードでは

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

たぶん、GameBoard を変更可能にしたいでしょう:

public class GameBoard {

    public GameBoard() {
        setLevel(1);
    }

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

    public void nextLevel() {
        setLevel(currentLevel+1);
    }
}
于 2013-02-28T19:48:50.847 に答える