java - 如何实现向对象实例添加值的默认接口方法
问题描述
如何实现 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
}
}
解决方案
您通常无法做到这一点;接口没有任何状态,“添加数字”的概念强烈暗示您希望更新状态。
这是一种方法:
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
(
推荐阅读
- python - 无法从 Python 中的函数返回值
- angular - 使用 cdk/ComponentPortal 动态添加组件
- excel - 运行时错误“91”:对象变量或未在 h = ie.hwnd 行上设置块变量
- objective-c - Xamarin 方法调配不起作用。为什么不?
- android - Koin 中的 DSL 有什么用?
- python - (Python)我需要删除列表中的重复元素(使用删除功能;避免类型转换)。试图确定为什么我的解决方案不正确
- c# - 实体框架错误删除具有外键的对象
- angular - 即使在 Angular 8 中的 ngAfterViewInit 上也未定义 ViewChild elementRef
- java - android Studio 的 DownloadManger 类中“外部”的确切参考是什么?
- javascript - ASP / HTML / Javascript 无法正常工作