Illegal static interface method call

廉价感情. 提交于 2019-11-28 00:04:00

问题


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

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

E.g.:

interface X {
    static void y() {
    }
}

...

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

causes error:

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/34709082/illegal-static-interface-method-call

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