Home > Software design >  Implement a method from an interface without overriding
Implement a method from an interface without overriding

Time:11-23

I have an interface WithNaturalCoordinates with method setX and a class that implements it (RepetitiveRobotImpl). That class (RepetitiveRobotImpl) also extends a class called Robot. Robot also has a method setX.

Now my question is, how do I implement the method setX without overriding the setX from Robot?

My interface:

public interface WithNaturalCoordinates {
void setX(int x);
}

The class Robot:

public void setX(int x) {
    world.trace(this, RobotAction.SET_X);
    setXRobot(x);
  }

The class which implements the interface:

public class RepetitiveRobotImpl extends Robot implements WithNaturalCoordinates {

  public RepetitiveRobotImpl(int numberOfRepetitions){
    super(0, 0, Direction.UP, 100);
  }

public void setX(int x) {
    if(x < 0) {
      super.setX(-x);
    }
    else {
      super.setX(x);
    }
  }

Here the method setX is kinda doing both implementing and overriding.

Sorry, if it sounds kinda weird, I'm new to Java & programming in general.

CodePudding user response:

Now my question is, how do I implement the method setX without overriding the setX from Robot?

You cannot. If you have two supertypes with a method with the same signature -- the same name, the same argument types -- you can't override one and not the other.

CodePudding user response:

The method inherited from the parent class is enough to implement the interface:

class RobotBase {
    int x;
    public void setX(int x) { this.x = x; }
}

interface IRobot {
    void setX(int x);
}

// no compilation error; the inherited method is sufficient to implement the interface
class Robot extends RobotBase implements IRobot {}
  • Related