Java 8 接口(interface)与抽象类

标签 java java-8

我经历了这个问题: 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/

相关文章:

java - 将 JList 值从 JFrame 传递到 JDialog

java - 当我在swt中拖动对话框时如何防止检查按钮移动?

Java流过滤器值的总和

java - 按字母顺序对列表进行排序,头部有特定值(如果存在)

oop - 两个默认方法互相调用

spring - Stream 和 Spring Data 的优点

java.util.date 到 String 使用 DateTimeFormatter

java - 如何在java中声明属性的可能值

Java - 突破入侵方法并返回值

java - 在java中读取大数据文件时的巨大内存开销