Search code examples
javastatic-methodsinterface-implementation

how to implement a static method in a class that implements an interface?


I'm implementing a java class that implements an interface.
The poi is that, a method in this class must be static, but in the interface I can't (as known) declare a method as static, and if I try to declare it in the class, I get this error: "This static method cannot hide the instance method from InterfaceName".

I've searched in this site but I haven't found any solution but a suggestion said to create an abstract class that implements the interface, and then extend the abstract one in the class, but it doesn't work.

Any suggestion?

Thanks a lot to everybody!


Solution

  • The link mvw posted ( Why can't I define a static method in a Java interface? ) describes the reason for not allowing static methods in interfaces and why overriding static methods iis not a good idea (and thus not allowed).

    It would be helpful to know in what situation you want to use the static method. If you just want to call a static method of the class, jut give it another name as andy256 suggested. If you want to call it from an object with a reference to the interface, do you really need the method to be static?

    To get around the problem, my suggestion is that if you really want to call a static method with the same signature as the interface method, call a private static method:

    class MyClass implememts SomeInterface {
    
        @Override
        public int someMethod(int arg1, int arg2) {
            return staticMethod(arg1, arg2);
        }
    
        private static int staticMethod(int arg1, int arg2) {
            // TODO: do some useful stuff...
            return arg1 + arg2;
        }
    }