I have several Java classes which contain static methods. I want to ensure that these static methods are implemented by each of the classes. How can I enforce that, since declaring static methods is not allowed in interfaces in Java?
-
1http://stackoverflow.com/questions/512877/why-cant-i-define-a-static-method-in-a-java-interface – brso05 Dec 04 '14 at 13:45
3 Answers
Sort answer: You can't enforce that.
Static methods are not inherited the same way as instance methods, so you wouldn't be able to use it for anything meaningful anyway: You can't call MySuperClass.staticMethod()
and expect some subclass to handle the call. This means that you have to call it using MySubClass.staticMethod()
in which case you'll get a compilation error if MySubClass
doesn't implement staticMethod
.
I would suggest you look into solving it using a singleton or factory pattern and use instance methods:
MySuperClass.getInstance(parameter).yourMethod()

- 413,195
- 112
- 811
- 826
static
methods are allowed on interfaces in Java8.
However, there's no way to enforce a class to implement a static method.
The only thing you can do, is make them non-static and abstract
(either in an interface or in an abstract
class).

- 62,134
- 8
- 100
- 147
If you have code that calls these methods, it won't pass compilation if they are not implemented. If you don't, you don't really need them.

- 387,369
- 54
- 702
- 768