Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal static interface method call

Tags:

java

java-8

jls

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?

like image 265
Andremoniy Avatar asked Jan 10 '16 18:01

Andremoniy


1 Answers

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.

like image 192
chrylis -cautiouslyoptimistic- Avatar answered Sep 17 '22 19:09

chrylis -cautiouslyoptimistic-