有 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.

我试着在默认方法中创建一个具体类(实现)的对象,并调用了它的实例方法,效果很好。i、 我不需要使用接口类型作为对象的引用

那么引用的段落是什么意思呢


共 (3) 个答案

  1. # 1 楼答案

    这句话意味着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();
      }
    }
    
  2. # 2 楼答案

    默认方法仅用于获得Backword_兼容性支持。请注意,默认方法的优先级低于普通方法(或更高级别的方法),因此无法实现更高级别和更方便的方法

  3. # 3 楼答案

    问题是,默认方法只能“看到”接口本身中声明的内容,而不能“看到”实现类中声明的内容。在实现该接口的类中声明的任何状态字段都是不可访问的。但他们可以访问接口的static final字段:

    interface test {
        static final int x = 3;
    
        public default void changeIt() {
            System.out.println(x); // this would work
            ++x; // this will fail
        }
    }