超类方法与接口默认方法冲突解决 [英] Super class method and Interface default method conflict resolution
问题描述
考虑下面的例子,
public class Testing extends SupCls implements Intf {
public static void main(String[] args) {
new Testing().test();
}
}
class SupCls {
public void test() {
System.out.println("From SupCls");
}
}
interface Intf {
public default void test() {
System.out.println("From Intf");
}
}
如您所见,SupCls
类和 Intf
接口之间没有联系.但两者都定义一种通用方法.
As you can see, there's no connection between SupCls
class and Intf
interface. But both are defining a common method.
和Testing
类正在扩展SupCls
并实现Intf
.
And Testing
class is extending SupCls
and implementing Intf
.
所以,当我在 Testing
上调用 test()
方法时,输出是,
So, when I call test()
method on Testing
the output is,
From SupCls
我认为这是有道理的,因为从类扩展应该比从接口实现具有更高的优先级.
Which I think makes sense because extending from a class should take higher priority than implementing from an interface.
但 eclipse 会报告其他情况,如下面的屏幕截图所示.
我坚信这是一个Eclipse 中的错误.
但在假设之前,此行为是否已定义&在 JLS 中记录?或者还有其他什么东西定义了这种行为?
But before assuming, is this behavior defined & documented in the JLS? Or is there something else which defines this behavior?
Eclipse 版本是 Mars Release (4.5.0),如果重要的话.
Eclipse version is Mars Release (4.5.0), if it matters.
推荐答案
你的假设是对的,从超类继承的具体方法优先于interface
中的default
方法代码>:
Your assumption is right, the concrete method inherited from the superclass takes precedence over the default
method from the interface
:
类C
从其直接超类和直接超接口继承所有抽象
和默认(第9.4节)方法m代码> 满足以下所有条件:
A class
C
inherits from its direct superclass and direct superinterfaces allabstract
and default (§9.4) methodsm
for which all of the following are true:
…
C
中声明的任何方法都没有作为m
签名的子签名(第 8.4.2 节)的签名.C
从其直接超类继承的具体方法没有一个签名,该签名是m
签名的子签名.
- No method declared in
C
has a signature that is a subsignature (§8.4.2) of the signature ofm
. - No concrete method inherited by
C
from its direct superclass has a signature that is a subsignature of the signature ofm
.
引用的第二个要点在这里适用,有一个从具有适当签名的直接超类继承的具体方法,因此default
方法没有被继承.
The second cited bullet applies here, there is a concrete method inherited from the direct superclass with an appropriate signature, so the default
method is not inherited.
文档甚至通过附加注释消除了任何疑问:
The documentation even clears any doubt with an additional remark:
请注意,继承的具体方法可能会阻止抽象或默认方法的继承.(稍后我们将断言具体方法覆盖来自 C"的抽象或默认方法.)
所以当涉及到 Testing
类时,它就像 SupCls.test()
覆盖了 Intf.test()
.
So it’s like SupCls.test()
overrides Intf.test()
when it comes to class Testing
.
换句话说,你是对的,这是 Eclipse 中的一个错误,但只要它只影响提案的呈现方式,我就会认为它是一个小错误.插入的来源将是相同的,无论提案中是否已呈现 D.
In other words, you are right, it’s a bug in Eclipse, but as long as it only affects the way the proposal is rendered, I’d consider it a minor bug. The inserted source will be the same, regardless of whether a D has been rendered in the proposal or not.
这篇关于超类方法与接口默认方法冲突解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!