为什么这个程序给出输出“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/