Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

java - Illegal static interface method call

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...