繁体   English   中英

从接口实现方法而不覆盖

[英]Implement a method from an interface without overriding

我有一个带有方法setXWithNaturalCoordinates接口和一个实现它的 class ( RepetitiveRobotImpl )。 那 class ( RepetitiveRobotImpl )也扩展了一个名为Robot的 class 。 Robot还有一个方法setX

现在我的问题是,如何在不覆盖RobotsetX的情况下实现方法setX

我的界面:

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

class Robot

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

实现接口的 class :

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);
    }
  }

这里的方法setX有点实现和覆盖。

抱歉,如果这听起来有点奇怪,我是 Java 和一般编程的新手。

现在我的问题是,如何在不覆盖 Robot 的 setX 的情况下实现方法 setX?

你不能。 如果您有两个具有相同签名的方法的超类型——相同的名称、相同的参数类型——你不能覆盖一个而不是另一个。

从父class继承的方法足以实现接口:

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 {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM