I am making a checkers game and have the following classes. Abstract class piece:
public abstract class Piece {
protected Position position;
private CheckersColor color;
public Piece(CheckersColor color, Position position) {
this.position = position;
this.color = color;
}
with some more methods.
The sub class Checker:
public class Checker extends Piece {
public Checker(CheckersColor color, Position position) {
super(color, position);
}
with also some more methods, and another sub class king:
public class King extends Piece {
public King(CheckersColor color, Position position) {
super(color, position);
}
public King(Piece checker) {
super(checker.getColor(), checker.position);
}
The checkers are stored in an array of type Piece
private Piece[] whiteCheckers;
and inserted by :
whiteCheckers[counter] = new Checker(Constants.COLOR_WHITE, tempPosition);
So far everything works, but when I try to change one of the checkers into a king I get an error:
Exception in thread "main" java.lang.ArrayStoreException: King
The code that causes the error:
whiteCheckers[i] = new King(piece);
I have tried a few different ways to store it, with casting, removing the checker and adding the king in the same spot and more with no luck.
That's really weird to me because the checkers were stored with no problem and king causes the error while they are both sub classes of Piece.
Thanks a lot!
EDIT:
public class Board {
private int size;
private Piece[] blackCheckers;
private Piece[] whiteCheckers;
private Piece[][] board;
public Board(int size) {
....(Some other code)
for (int k = 0; k < whiteCheckers.length; k++) {
board[whiteCheckers[k].position.getRow()][whiteCheckers[k].position.getColumn()] = whiteCheckers[k];
board[blackCheckers[k].position.getRow()][blackCheckers[k].position.getColumn()] = blackCheckers[k];
}
} else {
throw new RuntimeException("The size is either smaller than 4 or is not even");
}
}
....(Some more methods)
public void verifyCrown(Piece piece) {
if ((piece.getColor().equals(Constants.COLOR_WHITE) && piece.position.getRow() == 0)
|| piece.getColor().equals(Constants.COLOR_BLACK) && piece.position.getRow() == size - 1) {
if (piece.getColor().equals(Constants.COLOR_WHITE)) {
for (int i = 0; i < whiteCheckers.length; i++) {
if (whiteCheckers[i].equals(piece)) {
whiteCheckers[i] = new King(piece);
}
}
}
if (piece.getColor().equals(Constants.COLOR_BLACK)) {
for (int i = 0; i < blackCheckers.length; i++) {
if (blackCheckers[i].equals(piece)) {
blackCheckers[i] = new King(piece);
}
}
}
....
}
}
}