Your code without instanceof doesn't make much sense: you won't be able to pass a Piece as argument to any of the methods.
Your code with instanceof doesn't compile, because instanceof expects a class name, not an object.
I'm not sure if having subclasses for your pieces is a good idea. If you just need them to have another state, and not another behavior, then you should just have a color
field in Piece. Anyway, you could simply implement what you want with the following:
public abstract class Piece {
public abstract String getColor();
public final boolean isAlly(Piece otherPiece) {
return this.getColor().equals(otherPiece.getColor());
}
}
public class RedPiece extends Piece {
@Override
public String getColor() {
return "red";
}
}
If you don't have any getColor()
method, you can use this.getClass().equals(otherPiece.getClass())
, but that prevents you from having a BigRedPiece subclass, for example.