What are the rules to handle homonym inherited methods?

倾然丶 夕夏残阳落幕 提交于 2019-11-29 10:51:41

The JLS states (§9.4.1.3 paragraph 7):

When an abstract and a default method with matching signatures are inherited, we produce an error.

They then go on to explain why they chose this:

In this case, it would be possible to give priority to one or the other - perhaps we would assume that the default method provides a reasonable implementation for the abstract method, too. But this is risky, since other than the coincidental name and signature, we have no reason to believe that the default method behaves consistently with the abstract method's contract - the default method may not have even existed when the subinterface was originally developed. It is safer in this situation to ask the user to actively assert that the default implementation is appropriate (via an overriding declaration).

The general rule is that the definitions in a class take precedence over defender methods in an interface. If a method is declared abstract in a class, that overrules the existence of a default implementation in the interface.

Defender methods were introduced as a stopgap measure to allow the growth of interface APIs without breaking backwards compatibilty. The semantics had to be such that defender methods don't get in the way of any existing language rules.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!