【问题标题】:How to implement a default interface method that adds a value to the object instance如何实现向对象实例添加值的默认接口方法
【发布时间】:2020-04-01 20:40:54
【问题描述】:

如何实现 void add(Number number) 以便将数字添加到对象实例

public interface Numbers {
   static int toIntValue();
   static void fromIntValue(int value);
   default void add(Number number) {
        // what do i write here
    }
}

【问题讨论】:

  • 接口不知道对象状态。通常,add 也是一个抽象方法。为什么要在界面中实现它?
  • fromIntValue 的目的是什么?通常一个名为from 的方法会有一个返回值。
  • 它以int形式返回对象实例的值
  • 但正如@khelwood 所说,事实并非如此。返回类型为void。此外,这种方法通常是static
  • fromIntValue 它为对象实例分配参数值

标签: java methods interface overriding default


【解决方案1】:

你大多不能这样做;接口没有任何状态,“添加数字”的概念强烈暗示您希望更新状态。

这是一种方法:

public interface Number /* Isn't Numbers a really weird name? */ {
    int toIntValue();
    default int add(int otherValue) {
        return toIntValue() + otherValue;
    }
}

这里没有状态改变;而是返回一个新的 int。

这里的另一个问题是,抽象出数字类型的整个概念是 没有 add 的默认实现

这只是基本的数学。复数是一种数; 事先不了解复数,编写可以将 2 个复数相加的代码显然是不可能的。

可以做的是从其他原语中创建添加,除了'add'通常是方便的原语。例如,这里有一个可以作为默认方法工作的乘法,尽管它根本没有效率:

public interface Number {
    Number plus(Number a); /* an immutable structure makes more sense, in which case 'plus' is a better word than 'add' */
    default Number multiply(int amt) {
        if (amt == 0) return Number.ZERO; // Define this someplace.
        Number a = this;
        for (int i = 1; i < amt; i++) a = a.plus(this);
        return a;
    }
}

您在这里定义了乘以加号。

请注意,java 已经有一个抽象数字概念 (java.lang.Number),它实际上几乎什么都做不了,因为尝试像这样抽象数学在任何语言中都很难,尤其是在 java 中。

【讨论】:

  • 啊,你看,我被类名误导以为NumbersNumber 实例的容器。但是其他方法名真的不支持我的解释。
猜你喜欢
  • 2014-12-06
  • 2014-12-22
  • 2010-12-25
  • 2015-07-31
相关资源
最近更新 更多