我如何实现void add(Number number)以便将数字添加到对象实例中
public interface Numbers {
int toIntValue();
void fromIntValue(int value);
default void add(Number number) {
// what do i write here
}
}
您通常不能这样做;接口没有任何状态,“添加数字”的概念强烈暗示您希望更新状态。
这是一种方法:
public interface Number /* Isn't Numbers a really weird name? */ {
int toIntValue();
default int add(int otherValue) {
return toIntValue() + otherValue;
}
}
这里状态没有改变;而是返回一个新的int。
这里的另一个问题是提取数字类型的整个概念是没有add的默认实现]。
这只是基本数学。复数是一种数字。显然不可能编写将两个复数加在一起的代码[事先不了解复数
。您CAN
所做的是从其他原语中创建添加,除了'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 = 0; i < amt; i++) a = a.plus(this); return a; } }
这里您已经定义了加号的乘法。
[注意,Java已经有了一个抽象的数字概念(java.lang.Number
),它的确几乎无能为力,因为试图以任何一种语言来抽象这样的数学运算都很难,尤其是在Java中。
您通常不能这样做;接口没有任何状态,“添加数字”的概念强烈暗示您希望更新状态。
这是一种方法:
public interface Number /* Isn't Numbers a really weird name? */ {
int toIntValue();
default int add(int otherValue) {
return toIntValue() + otherValue;
}
}
这里状态没有改变;而是返回一个新的int。
这里的另一个问题是,整个数字类型的抽象概念是没有默认的add可用实现。
这只是基本数学。复数是一种数字。显然不可能编写将两个复数加在一起的代码[事先不了解复数。
您CAN所做的是从其他原语中创建添加,除了'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 = 0; i < amt; i++) a = a.plus(this);
return a;
}
}
这里您已经定义了加号的乘法。
[注意,Java已经有了一个抽象的数字概念(java.lang.Number
),它的确几乎无能为力,因为试图以任何一种语言来抽象这样的数学运算都很难,尤其是在Java中。