Reputation: 1163
I have a class that is handling printing the various messages into the console, lets call this class ConsoleMessages.java. This class is public and abstract and all its methods are public and static.
I want to make an interface to this class (lets call it PrintMessages). I mean so, that ConsoleMessages.java will implement PrintMessages.
The thing is, JAVA doesn't support static methods in an interface.
What would you advise me to do?
Upvotes: 0
Views: 2616
Reputation: 74800
Interfaces are there to specify methods for objects (which will then be implemented by some class). You have no objects here, thus you need no interface.
Static methods can only be called using the exact class name (or alternatively the name of some subclass), there is no point in using an interface to do this.
So, you have two options:
Upvotes: -1
Reputation: 45453
There is really no strong arguement against static methods in interface. Nothing bad would happen.
An interface can have static fields and static member classes though, therefore static methods can be attached through them, albeit with one extra indirection.
interface MyService
static public class Factory
static public MyService get(...)
return ...;
MyService service = MyService.Factory.get(args);
Upvotes: 1
Reputation: 105258
Create the PrintMessages
interface with the methods you desire.
Make ConsoleMessages
a class that implements that interface. Change all methods from static to non static.
Enforce ConsoleMessages
instantiation as a singleton. This can be achieved in many ways, either doing it yourself or using a Dependency Injection framework.
Upvotes: 3
Reputation: 80633
If you find yourself needing to define interfaces on a utility class then it may be time to revisit your design choices. Your ConsoleMessages class seems to have outgrown its initial use as a dumping ground for 'common utility functions'.
Short answer? Refactoring time.
Upvotes: 0