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

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

    Several answers have discussed the problems with the concept of overridable static methods. However sometimes you come across a pattern where it seems like that's just what you want to use.

    For example, I work with an object-relational layer that has value objects, but also has commands for manipulating the value objects. For various reasons, each value object class has to define some static methods that let the framework find the command instance. For example, to create a Person you'd do:

    cmd = createCmd(Person.getCreateCmdId());
    Person p = cmd.execute();
    

    and to load a Person by ID you'd do

    cmd = createCmd(Person.getGetCmdId());
    cmd.set(ID, id);
    Person p = cmd.execute();
    

    This is fairly convenient, however it has its problems; notably the existence of the static methods can not be enforced in the interface. An overridable static method in the interface would be exactly what we'd need, if only it could work somehow.

    EJBs solve this problem by having a Home interface; each object knows how to find its Home and the Home contains the "static" methods. This way the "static" methods can be overridden as needed, and you don't clutter up the normal (it's called "Remote") interface with methods that don't apply to an instance of your bean. Just make the normal interface specify a "getHome()" method. Return an instance of the Home object (which could be a singleton, I suppose) and the caller can perform operations that affect all Person objects.

提交回复
热议问题