首页 > 解决方案 > 如何实现向对象实例添加值的默认接口方法

问题描述

如何实现 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
    }
}

标签: javamethodsinterfaceoverridingdefault

解决方案


您通常无法做到这一点;接口没有任何状态,“添加数字”的概念强烈暗示您希望更新状态。

这是一种方法:

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

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

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

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

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

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


推荐阅读