Reputation: 688
I have one superclass and serveral subclasses that extends the superclass. When I extend the abstract method in subclasses, I use a variable that looks exactly the same in other subclasses.
Usually, I would just make this as a global variable so that I don't have to duplicate the code, but I am not sure how to do this in my case because I am using the parameters in the variable.
For example,
public abstract boolean canMove(Piece[][] board, int fromX, int fromY, int toX, int toY);
//This is the abstract method in the super class
@Override
public boolean canMove(Piece[][] board, int startX, int startY, int endX, int endY) {
boolean onBound = (0 <= endX && endX < Board.NUM_OF_ROWS) && (0 <= endY && endY < Board.NUM_OF_COLS);
.....
}
Here is the implemented abstract method in a subclass. If I put this outside, it won't work since it is using the parameters. Is there a good way to prevent duplication of this line in other subclasses that share the common superclass??
Upvotes: 0
Views: 141
Reputation: 1218
write this in super class
public boolean canMove(Piece[][] board, int startX, int startY, int
endX, int endY) {
boolean onBound = (0 <= endX && endX < Board.NUM_OF_ROWS) && (0 <= endY && endY < Board.NUM_OF_COLS);
anotherMethod(onBound, any_other_parameters);
}
//override in subclass
@Override
anotherMethod(onBound , parma){
//your code
}
Upvotes: 1