I’ve read around that instead of using instanceof and getClass methods to implement polymorphism, as it’s better object-oriented practice.
If my program looks like the following:
Piece
SlowPiece extends Piece,
FastPiece extends Piece,
SlowFlexible extends SlowPiece,
FastFlexible extends FastPiece
And I have the following rule: SlowPiece's can only move one space, and FastPiece's as many as they'd like.
How would I use polymorphism to ensure that if I’m moving a Piece like Piece piece1 = new SlowPiece(); that it is not moved more than one?
I’ve got a class for the game-board, and it should be able to move the piece, but I’m not sure how to stop it from moving a SlowPiece more than 1 without code-sniffing.
Basically, I get how polymorphism is fantastic for say, listing things, but with actually interacting with them I don’t get how to use it properly.
Make
Pieceabstract and add an abstract methodmove()toPiece(you could also user an interface). Implementmove()differently (aSlowPieceonly moves 1 spot, etc).Here,
move()has all the moving logic; you could even use some overloads to allow for movement variety (like take N/S/W/E as arguments, etc).