Calling the illegal static interface method

Java-8 allows you to define static methods inside an interface, but restricts its invocation only to the interface name:

9.4: the interface can declare static methods that are called without reference to a specific object.

eg:.

interface X { static void y() { } } ... X x = new X() {}; xy(); 

causes an error:

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

Often in JLS, such prohibitions have an explanation. In this case, I did not find anything detailed. Therefore, I am looking for a comprehensive or authoritative explanation of this rule: why is it forbidden to refer to a static method through a specific object reference? What will he break?

+8
java java-8 jls
source share
1 answer

This is a pretty strong consensus that this syntax should not be allowed for static methods on classes, but by the time this was implemented, it was too late to change. It was not too late for the recently added interface methods.

In addition, by resolving this syntax, there was the possibility of a problem with diamond, since the class could implement interfaces that define counter methods.

+16
source share

All Articles