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

后端 未结 24 1501
没有蜡笔的小新
没有蜡笔的小新 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:33

    Something that could be implemented is static interface (instead of static method in an interface). All classes implementing a given static interface should implement the corresponding static methods. You could get static interface SI from any Class clazz using

    SI si = clazz.getStatic(SI.class); // null if clazz doesn't implement SI
    // alternatively if the class is known at compile time
    SI si = Someclass.static.SI; // either compiler errror or not null
    

    then you can call si.method(params). This would be useful (for factory design pattern for example) because you can get (or check the implementation of) SI static methods implementation from a compile time unknown class ! A dynamic dispatch is necessary and you can override the static methods (if not final) of a class by extending it (when called through the static interface). Obviously, these methods can only access static variables of their class.

提交回复
热议问题