In java 8, why cannot call the interface static method that the current class is implementing [duplicate]

余生长醉 提交于 2020-01-01 07:32:07

问题


I'm playing around Java 8's new features recently and observed an interesting behaviour:

This is okay:

Class A { static void staticMethodInA() {println();} }
Class B extends A {}

B.staticMethodInA();

This would induce an error of: static method may be invoked on containing interface class only.

interface A { static void staticMethodInA() {println();} }
Class B implements A {}

B.staticMethodInA(); // from here IntelliJ complaints..

Can someone tell me why the designer of Java 8 may choose to treat the above 2 cases differently?


回答1:


Addition of static methods in interface in Java 8 came with 1 restriction - those methods cannot be inherited by the class implementing it. And that makes sense, as a class can implement multiple interface. And if 2 interfaces have same static method, they both would be inherited, and compiler wouldn't know which one to invoke.

However, with extending class, that's no issue. static class methods are inherited by subclass.

See JLS §8.4.8:

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass

...

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (§9.4) methods m

...

A class does not inherit static methods from its superinterfaces.



来源:https://stackoverflow.com/questions/29383083/in-java-8-why-cannot-call-the-interface-static-method-that-the-current-class-is

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