I just recently started learning java, so I'm having a little trouble understanding what I think is a polymorphism issue. I'm trying to program a chess game, so I have a an array of superclass called GamePiece for which the subclass PawnPiece extends. I have a method in both classes called MovePiece() which changes the position of the piece. When I use MovePiece(), changes the position values of the PawnPiece, but when I try to call the positions in my main code, it gives me the unchanged position of 'GamePiece'. Here's some of my code:
public class GamePiece {
int position;
//Constructor
public GamePiece(int x){
position=x;
}
public void MovePiece(int positionOfMove){};
}
public class PawnPiece extends GamePiece{
int positionPawn;
//Subclass Constructor
public PawnPiece(int x){
super(x);
}
public void MovePiece(int positionOfMovePawn){
positionPawn=x;
}
public classChessMain{
public static void main(String[] arg){
GamePiece[] allPieces = new GamePiece[32];
int startPositionPawn = 9; //Arbitrary#
allPieces[8]=new PawnPiece(int startPositionPawn); //index is arbitrary
int playerMove = 5; //Arbitrary#
allPieces[8].MovePiece(playerMove);
}
}
The last line gives me the initial position (9 in this case), but I know if I could access the position of PawnPiece, it would give me 5. Any help all you coding wizards out there? I'd really appreciate it.
A couple issues:
GamePiece and the method MovePiece should be abstract. This way, you will force any subclass that chooses to be a GamePiece to implement its own MovePiece method.You are storing the position in two places:
int position in GamePieceint positionPawn in PawnPiece.You probably want only one of these: get rid of the positionPawn in PawnPiece and use position in GamePiece.
MovePiece to movePieceFrom the code given I can guess that in the PawnPiece you are updating variable positionPawn, and then check variable position. So you are writing to wrong place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With