我经历了这个问题: Interface with default methods vs Abstract class in Java 8
以下部分我不清楚:
The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.
我尝试在默认方法中创建一个具体类(实现)的对象并调用它的实例方法,它工作正常。即,我不需要使用接口(interface)类型作为对象的引用。
那么引用的段落是什么意思。
最佳答案
这句话意味着 default
方法是在接口(interface)内部实现的,因此它无法访问对象的真实状态,只能访问接口(interface)本身公开的内容,因为接口(interface)不能声明实例变量。
例如:
abstract class Foo {
int result;
int getResult() { return result; }
}
这不能在 interface
中完成,因为您不能有任何成员变量。你唯一能做的就是组合多个接口(interface)方法,这就是它被指定为方便/更高级别的方法,例如:
interface Foo {
void preProcess();
void process();
void postProcess();
default void processAll() {
preProcess();
process();
postProcess();
}
}
关于Java 8 接口(interface)与抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47331643/