Search code examples
javaclassabstract-classabstractsuperclass

How to make a method from abstract super class to work for subclasses


I am making a chess game and tried using an inheritance desing for all the pieces. I want to make the subclass pawn use the method printPiece from Piece, but I have to modify the parameters on each piece. I know it's a bit silly to have the same parameters on both classes, but I don't know how to make the superclass use the print method without declaring icon in it. Same if i want to create getters on the superclass, the subclasses don't recognize them.

I have tried the code provided and it doesn't recognize that icon is 'i' from a pawn, it just uses the superclass method and writes null. Also tried making the parameters protected but same result.

public abstract class Piece{
    private String name;
    private int value;
    private boolean alive;
    private char icon;

    public Piece() {}

    public abstract Coordinate movePiece(Coordinate coor);

    public abstract boolean canMovePiece();

    public void printPiece()
    {
        System.out.print(icon);
    }
}

public class Pawn extends Piece {
    private String name;
    private int value;
    private boolean white;
    private char icon;

    public Pawn(boolean pWhite) {
        super();
        this.value = 1;
        this.name = "Pawn";
        this.white = pWhite;
        if(pWhite) {this.icon = 'I';}
        else {this.icon = 'i';}
    }

    public Coordinate movePiece(Coordinate coor){}

    public boolean canMovePiece() {}
}

Solution

  • When you extend Piece, you want to inherit the things in Piece that are common to all subclasses of Piece. So you don't re-declare variables in Pawn.

                public class Piece
                {
                    private char icon;
                    public char getIcon() { return icon; }
                    public void setIcon(char i) { icon = i; }
                    public Piece(char c) { setIcon(c); }
                }
    
                public class Pawn extends Piece
                {
                    public Pawn()
                    {
                        super('I');
                    }
                }
    

    This is a way to have every subclass have an icon, stored in Piece, and ways to set it and access it.