Home > front end >  Interfaces and static methods in java
Interfaces and static methods in java

Time:05-15

It occurred to me that interfaces cannot be instantiated and hence I could create an interface containing only a bunch of static utilities methods that I need as opposed to a regular class with a private constructor and public static methods. Any comments on that? Should I do it or does it not really matter?

CodePudding user response:

A program is not just a set of instructions for a computer to obey. It's also a message to future developers. You should use the statements in your program to indicate to other developers (or even yourself a few months into the future), what you intend for the computer to do.

That's why we give variables, methods and classes clear names. It's why we lay out our programs in certain expected ways. It's why we use indentation consistently, and why we have naming conventions.

One of those conventions is that if you have a bunch of static methods that need to be organised together, they should be organised into a class, not an interface. Whether or not it's technically possible to put all your methods into an interface is not the question you should be asking. What matters is how to communicate most efficiently what you're actually intending to do.

To that end, please don't set up your program in strange, innovative ways. You're just going to confuse and annoy people.

CodePudding user response:

Although this is possible interfaces should be used

when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.

https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

Interfaces should be defined as an abstract type used to specify the behavior of a class; therefore they're meant to be later implemented.

What you're trying to do is not completely wrong (interfaces can offer static methods), but it's definitely not what they were designed for. If you want to offer a set of static utilities from a common "place", you could declare a final class with a private constructor, in order to prevent its extension (with possible methods overriding), and avoid its instantiation- The Math class is a perfect example of this.

Alternatively, if you want to declare instances of said class, you could declare your class normally, then declare its methods as static (to prevent their overriding) and offer a public constructor or a factory method.

  • Related