Skip to content
Advertisement

Set parent class attribute in a child class

I trying to make a chess game and I will have a class for each chess piece but they will all extend class Piece. Piece class has a maxMovementDistance attribute but I would like to set that attribute in the child class (king, queen, pawn etc.) and it should also be final.

What’s the best way to do this?

Or should I change my implementation?

public class Piece {

int maxMovementDistance;
private boolean isWhite = false;
private boolean isKilled = false;
private boolean canMoveBack = true;
private int positionX;
private int positionY;
}

public class King extends Piece {

}

Advertisement

Answer

This would normally be done by creating a constructor in the superclass that sets the values via parameters you pass into it and then calling that constructor from the subclass.

eG

public class Piece {

    private final int maxMovementDistance;

    public Piece(int maxMovementDistance) {
        this.maxMovementDistance = maxMovementDistance;
    }

    public int getMaxMovementDistance() {
        return this.maxMovementDistance;
    }
}



public class King extends Piece {

      public King() {
           super(1); // will call super constructor with 1 as argument pased
      }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement