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 {
}
CodePudding user response:
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
}
}
CodePudding user response:
Make the members of the base class protected so that way only the descendants can access and modify the values.