Is there a way to make sure classes implementing an Interface implement static methods?

后端 未结 9 1945
礼貌的吻别
礼貌的吻别 2021-01-07 17:11

First of all, I read erickson\'s useful reply to \"Why can’t I define a static method in a Java interface?\". This question is not about the \"why\" but about the \"how then

9条回答
  •  一整个雨季
    2021-01-07 17:46

    Your answer to your own question can be simplified further. Keep the ParametricFunction interface as-is, and change Parabola into a singleton that implements ParametricFunction:

    public class Parabola implements ParametricFunction {
      private static Parabola instance = new Parabola();
    
      private Parabola() {}
    
      static public ParametricFunction getInstance() {
        return instance;
      }
    
      public double getValue(double x, double[] parameters) {
        return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
      }
      public String getName() { return "Parabola"; }
      public boolean checkParameters(double[] parameters) {
        return (parameters.length==3);
      }
    }
    

    Indeed, if there is no particular reason why Parabola needs to be a singleton class, you could get rid of the static method and attribute and make the constructor public.

    The purpose of creating an instance of Parabola is to simplify your application.

    EDIT in response to your question below:

    You cannot use standard Java constructs to force a class to implement a static method with a given signature. There is no such thing as an abstract static method in Java.

    You could check that a static method is implemented by writing a separate tool that runs as part of your build and checks either the source code or the compiled code. But IMO, it is not worth the effort. Any missing getInstance() will show up if you compile code that calls it, or at runtime if you try to use it reflectively. That should be good enough, in my opinion.

    Besides, I cannot think of a convincing reason why you need the class to be a singleton; i.e. why the getInstance method is necessary.

提交回复
热议问题