为什么可以使用默认方法的接口签名来访问类方法?

问题描述 投票:2回答:2

也许这个问题有明显的答案,但我找不到它可能是因为我是一个java新手。您能否说一下为什么在Java中可以使用默认方法的接口签名来访问类方法。我认为只能从类实例访问方法。例:

public interface test {

   String voo();

   default void foo() {
       voo().toString();
   }
}
java methods interface default
2个回答
0
投票

根据JLS 9.4.3. Interface Method Body,不禁止在默认接口方法体内调用另一个方法:

默认方法有一个块体。如果类实现接口但不提供自己的方法实现,则此代码块提供方法的实现。

在实践中,默认方法与类方法没有什么不同,特别是在Java 9可以拥有私有接口方法时:

public interface Test {

  String voo();

  default void foo() {
   bar();
  }

  private void bar() {
    voo().toString();
  }
}

0
投票

默认方法是实例方法。 (JLS 9.4: Method declarations

在特定的对象实例上调用实例方法。但是通过引用声明该方法的类型的对象来调用实例方法。该类型可能是运行时实际对象类型的超类或接口。

这允许我们编写可以通过公共接口操作多种类型对象的代码 - 一种多态。

在实例方法中,您可以调用可通过包含调用实例方法的类型访问的其他实例方法。

(可选)您可以通过关键字this执行此操作,该关键字定义为对调用实例方法的对象的引用,该关键字出现的类型。 this关键字可用于默认方法。 (JLS 15.8.3: this

因此,在您的情况下,您的默认方法可以调用this.voo()或只调用voo()

public interface test {
   String voo();

   default void foo() {
      this.voo().toString(); // Can call an instance method accessible through this type.
      voo().toString();      // Equivalent call
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.