public void movePiceTo(int x, int y, Piece pieceToMove) {

    if(pieceToMove.canMove(board, pieceToMove.getX(), pieceToMove.getY(), x, y)){ //Check if the piece canMove to the location

        if(board[x][y] == null) { //Check if the location is empty

            removePiece(pieceToMove.getX(), pieceToMove.getY());
            board[x][y] = pieceToMove;

            if(pieceToMove instanceof Pawn) {
                pieceToMove = (Pawn)pieceToMove;
                pieceToMove.isFirstMove = false;
            }


此代码段控制棋子的移动。在最后三行,它试图将Pawn类的isFirstMove变量更改为false,因为这不再是Pawn的第一步。但是我很难更改变量,因为pieceToMove对象基本上是Piece类(Pawn的超类),而不是Pawn类。我该如何顺利进行?

最佳答案

您将pieceToMove强制转换为Pawn,但是变量的类型仍然是Piece

试试这个:

if(pieceToMove instanceof Pawn) {
    Pawn pawnToMove = (Pawn) pieceToMove;
    pawnToMove .isFirstMove = false;
}

10-05 17:46