java - "default"(接口(interface))是如何工作的?

标签 java

为什么这个程序给出输出“Class A”?

abstract class A {
      public void abc() {
        System.out.println("Class A");
      }
    }         
    interface B {
      default void abc() {
        System.out.println("Interface B");
      }
    }
    public class Test extends A implements B {
      public static void main(String[] args) {
        Test t = new Test();
        t.abc();
      }
    }

有谁能解释一下吗?

最佳答案

虽然抽象类和接口(interface)都有相同的方法,但抽象类方法在运行时选择时优先级高。

这是 JLS on Method invocation principles

It is possible that no method is the most specific, because there are two or more methods that are maximally specific. In this case:

If all the maximally specific methods have override-equivalent signatures (§8.4.2), then:

If exactly one of the maximally specific methods is concrete (that is, non-abstract or default), it is the most specific method.

Otherwise, if all the maximally specific methods are abstract or default, and the signatures of all of the maximally specific methods have the same erasure (§4.6), then the most specific method is chosen arbitrarily among the subset of the maximally specific methods that have the most specific return type.

In this case, the most specific method is considered to be abstract. Also, the most specific method is considered to throw a checked exception if and only if that exception or its erasure is declared in the throws clauses of each of the maximally specific methods.

Otherwise, the method invocation is ambiguous, and a compile-time error occurs.

关于java - "default"(接口(interface))是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036233/

相关文章:

java.lang.OutOfMemoryError : Physical memory usage is too high: physicalBytes (1100M) > maxPhysicalBytes (1024M)

java - 让每个实现接口(interface)的类都调用一个方法?

java - Spring data - 启用乐观锁定

java - 给定两个随机整数数组,打印它们的交集。也就是说,打印两个给定数组中存在的所有元素

java - STS映射 Controller 查看

java - 通过每次用户输入相应值时添加一张卡片来创建一副卡片

java - servlet init 方法无法创建 mysql 表 - 为什么?

java - 如何使用html表单发送的XML?

java - 如何测试Spring Webmvc webservice rest

java - 如何从给定的日期集中查找每个月的最少日期