【问题标题】:Implement a method from an interface without overriding从接口实现方法而不覆盖
【发布时间】:2022-01-01 08:36:21
【问题描述】:

我有一个接口 WithNaturalCoordinates 和方法 setX 和一个实现它的类 (RepetitiveRobotImpl)。该类 (RepetitiveRobotImpl) 还扩展了一个名为 Robot 的类。 Robot 还有一个方法setX

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

我的界面:

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

班级Robot

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

实现接口的类:

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 和一般编程的新手。

【问题讨论】:

  • 你想做什么? (你可以使用super.setX(Math.abs(x));
  • 也许你希望父类Robot实现接口?
  • 由于它是相同的方法签名,您的方法将覆盖 两种类型的setX,并且没关系。您实际上想要达到什么目的?你想解决什么问题?
  • 现在你的问题看起来像XY problem。尝试edit 它并阐明您想要实际实现的目标。

标签: java overriding implementation


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-20
      • 2021-11-02
      • 2011-08-04
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多