Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Subclass Field from Array of Superclass?

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.

like image 792
Scrantonicity83 Avatar asked Dec 05 '25 08:12

Scrantonicity83


2 Answers

A couple issues:

  1. The class 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.
  2. You are storing the position in two places:

    • You have int position in GamePiece
    • You have int positionPawn in PawnPiece.

    You probably want only one of these: get rid of the positionPawn in PawnPiece and use position in GamePiece.

  3. (Optional) Java convention is to have method names begin with a lower case letter: rename MovePiece to movePiece
like image 76
cklab Avatar answered Dec 07 '25 22:12

cklab


From 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.

like image 36
jdevelop Avatar answered Dec 07 '25 20:12

jdevelop