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!

6
  • Either use different name or different argument list. Commented Jul 31, 2013 at 12:26
  • 1
    do you have to override the static method? i don't think that is even allowed in java Commented Jul 31, 2013 at 12:28
  • 2
    stackoverflow.com/questions/512877/… Commented Jul 31, 2013 at 12:28
  • Hiding an instance method with a static method is confusing. Either remove the method from the interface or refrain from using the same name for your static method. Commented Jul 31, 2013 at 12:35
  • so I can't have a static method in a class that implements an interface? Commented Jul 31, 2013 at 12:35

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.