我回答了这个问题:Interface with default methods vs Abstract class in Java 8
以下部分我不太清楚:
默认方法的约束是,它只能在调用其他接口方法的条件下实现,而不引用特定实现的状态。因此,主要的用例是较高层次和方便的方法.
我尝试在默认方法中创建具体类(实现)的对象,并调用它的实例方法,它运行良好。也就是说,我不需要使用接口类型作为对象的引用。
那么,引用的段落是什么意思呢?
发布于 2017-11-16 14:08:58
这句话意味着default方法是在接口中实现的,因此它不能访问对象的真实状态,而只能访问接口本身公开的内容,因为接口不能声明实例变量。
例如:
abstract class Foo {
int result;
int getResult() { return result; }
}这不能在interface中完成,因为您不能有任何成员变量。您唯一能做的就是将多个接口方法组合起来,这就是被指定为方便/高级方法的方法,例如:
interface Foo {
void preProcess();
void process();
void postProcess();
default void processAll() {
preProcess();
process();
postProcess();
}
}发布于 2017-11-16 14:15:32
问题是,默认方法只能“查看”接口本身声明的内容,而不是在实现类中声明。实现此接口的类中声明的任何状态字段都是不可访问的。但是他们可以访问接口的static final字段:
interface test {
static final int x = 3;
public default void changeIt() {
System.out.println(x); // this would work
++x; // this will fail
}
}发布于 2018-09-23 02:02:14
默认方法仅用于获得Backword_Compatibility支持。请注意,默认方法的优先级低于常规方法(或更高级别的方法),因此无法实现更高级别和更方便的方法。
https://stackoverflow.com/questions/47331643
复制相似问题