简体   繁体   中英

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() {}
}

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.

By declaring a private char icon in the super class, you prevent the subclass from accessing it.

Instead of re-declaring a private char icon in the subclass, which is shadowing the parent's variable, you can declare a setter, or make it part of the parent's constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM