0

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??

9
  • I don't understand your issue. Is it with the method declaration (canMove) or the onBound calculation Commented Sep 15, 2017 at 5:03
  • Sorry. I just wanted to avoid duplicating onBound declaration on other subclasses. Commented Sep 15, 2017 at 5:05
  • You can create a method in the super class that says onBound and have the logic inside. However If you don't want to see that variable at all, then you have to start templating your code. search for common lines of code and make them abstract then keep the general form for the canMove Commented Sep 15, 2017 at 5:06
  • Is the expression on the right side of = the same in all the classes? Commented Sep 15, 2017 at 5:07
  • 1
    use a different method to calculate onBound varaible with parameters and create other method with no parameters to use it, so you will have to write code of second method in subclasses and you can use first method as it is Commented Sep 15, 2017 at 5:08

1 Answer 1

1

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
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.