3

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!

cokeman19
  • 2,405
  • 1
  • 25
  • 40
idell
  • 107
  • 1
  • 2
  • 13

1 Answers1

4

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;
    }
}
BeUndead
  • 3,463
  • 2
  • 17
  • 21
Icermann
  • 181
  • 3
  • 2
    but in this way you can't use the method statically, MyClass.someMethod(1, 2) is not allowed. You need to have a instance of MyClass to call the someMethod. – Paul Marcelin Bejan Nov 03 '22 at 12:28