非法的静态接口方法调用 [英] Illegal static interface method call

查看:551
本文介绍了非法的静态接口方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java-8允许在接口内定义静态方法,但仅通过接口名称限制它的调用:

Java-8 allows define static methods inside interface, but restricts it invocation by only interface name:


9.4:接口可以声明静态方法,无需$ b $即可调用b对特定对象的引用。

9.4: An interface can declare static methods, which are invoked without reference to a particular object.

例如:

interface X {
    static void y() {
    }
}

...

X x = new X() {};
x.y();

导致错误:

error: illegal static interface method call
        x.y();
            ^
  the receiver expression should be replaced with the type qualifier 'X'

通常在JLS中,这种禁令有一个解释。在这种情况下,我没有发现任何详细的信息。所以我正在寻找对此规则的全面或权威解释:为什么禁止通过特定对象引用调用静态方法?它破坏了什么?

Often in JLS such kind of prohibitions have an explanation. In this case I didn't found anything detailed. So I'm looking for a comprehensive or authoritative explanation of this rule: why it is prohibited to invoke static method via particular object reference? What does it break?

推荐答案

这是一个相当强烈的共识,即静态方法不应该允许有问题的语法班级,但是到了实现的时候,改变已经太晚了。对于最近添加的界面方法来说还不算太晚。

It's a fairly strong consensus that the syntax in question shouldn't have been allowed for static methods on classes, either, but by the time that was realized it was too late to change. It wasn't too late for the recently added interface methods.

此外,允许这种语法会引入钻石问题的可能性,因为类可以实现定义冲突方法的接口。

Additionally, permitting this syntax would introduce the possibility of the diamond problem, as a class could implement interfaces defining colliding methods.

这篇关于非法的静态接口方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆