user6792790
user6792790

Reputation: 688

How to avoid using same variable in different classes in Java?

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

Answers (1)

Ganesh Karewad
Ganesh Karewad

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

Related Questions