Accessing a subclass field from a superclass array?
I recently started learning Java, so I am having trouble understanding what I consider to be a polymorphism problem. I am trying to program a chess game, so I have a superclass array called GamePiece
, for which the subclass is being extended PawnPiece
. I have a method in both classes called MovePiece()
that changes the position of the part. When I use MovePiece()
, it changes the position values PawnPiece
, but when I try to call the positions in my main code, it gives me the unchanged "GamePiece" position. Here are 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 starting position (9 in this case), but I know if I can access the position PawnPiece
, that would give me 5. Any help getting you all to code the wizards there? I would really appreciate it.
source to share
A couple of questions:
- Class
GamePiece
and methodMovePiece
must be abstract. This way you will enforce any subclass it choosesGamePiece
to implement its own methodMovePiece
. -
You store the position in two places:
- You have
int position
toGamePiece
- You have
int positionPawn
toPawnPiece
.
You probably only need one thing: get rid of
positionPawn
inPawnPiece
and useposition
inGamePiece
. - You have
- (Optional) It is a Java convention that method names begin with a lowercase letter: rename
MovePiece
toMovePiece
source to share