Why can't I define a static method in a Java interface?

后端 未结 24 1102
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 05:44

EDIT: As of Java 8, static methods are now allowed in interfaces.

Here\'s the example:

public interface IXMLizable         


        
24条回答
  •  渐次进展
    2020-11-22 06:41

    This was already asked and answered, here

    To duplicate my answer:

    There is never a point to declaring a static method in an interface. They cannot be executed by the normal call MyInterface.staticMethod(). If you call them by specifying the implementing class MyImplementor.staticMethod() then you must know the actual class, so it is irrelevant whether the interface contains it or not.

    More importantly, static methods are never overridden, and if you try to do:

    MyInterface var = new MyImplementingClass();
    var.staticMethod();
    

    the rules for static say that the method defined in the declared type of var must be executed. Since this is an interface, this is impossible.

    The reason you can't execute "result=MyInterface.staticMethod()" is that it would have to execute the version of the method defined in MyInterface. But there can't be a version defined in MyInterface, because it's an interface. It doesn't have code by definition.

    While you can say that this amounts to "because Java does it that way", in reality the decision is a logical consequence of other design decisions, also made for very good reason.

提交回复
热议问题