Reputation: 11317
I'm making a chess game and each Piece has a subclass - King, Queen, Rook etc
Each Piece has a playerId attribute which I want to set like this:
public abstract class Piece {
private int playerId;
public Piece(int playerId) {
this.playerId = playerId;
}
}
But this only works if I instantiate Piece directly (which I can't anyway, because it's abstract). Is there a way to make this constructor apply to ALL subclasses, without having to manually implement it in each class?
Upvotes: 1
Views: 227
Reputation: 18435
You might want to think about static factory methods.
public abstract class Piece
{
private int playerId;
public int getPlayerId()
{
return playerId;
}
public int setPlayerId(int playerId)
{
this.playerId = playerId;
}
}
public class King extends Piece
{
//King specific stuff in here
}
public class ChessFactory
{
public static King newKing(int id)
{
King king = new King();
king.setId(id);
return king;
}
}
Upvotes: 1
Reputation: 89169
One way (The way I usually do this) is to have a protected piece constructor
public abstract class Piece {
private int playerId;
protected Piece(int playerId) {
this.playerId = playerId;
}
}
and for every subpiece, e.g. Rook
public class Rook extends Piece {
public Rook(int playerId) {
super(playerId);
}
}
That way, the constructor for Piece
is indeed to everyone except its descendants.
Upvotes: 0
Reputation: 47373
There is no easy way. In each of the descendants write something like this:
public Rook(int playerId) {
super(playerId);
}
Upvotes: 1
Reputation: 533492
Usually, your IDE can do this for you. When you extend Piece it should offer to add all the constructors you need. It still needs to be done, but avoids having to do it manually.
Perhaps you can avoid sub-classing Piece by making seperating its behaviour from the Pieces.
enum PieceType {
KING, QUEEN, ROOK;
}
public class Piece {
private final PieceType pieceType;
private final String playerId;
public Piece ... // one constructor for all.
}
Upvotes: 1