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.

+3


source to share


2 answers


A couple of questions:



  • Class GamePiece

    and method MovePiece

    must be abstract. This way you will enforce any subclass it chooses GamePiece

    to implement its own method MovePiece

    .
  • You store the position in two places:

    • You have int position

      toGamePiece

    • You have int positionPawn

      to PawnPiece

      .

    You probably only need one thing: get rid of positionPawn

    in PawnPiece

    and use position

    in GamePiece

    .

  • (Optional) It is a Java convention that method names begin with a lowercase letter: rename MovePiece

    toMovePiece

+2


source


From the code above, I can guess that in the PawnPiece you update the positionPawn variable and then check the position variable . So you are writing in the wrong place.



+1


source







All Articles