开发者

Advice needed: static methods in JAVA interface

开发者 https://www.devze.com 2023-03-24 03:39 出处:网络
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 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开发者_如何学Python 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?


  • 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.


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);


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.


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:

  • Throw your interface away and stay with the static methods.
  • Make all methods (or at least these which should be in the interface) non-static, and your implementing class non-abstract. To call them one then would need an object of the class (implementing this interface).
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号