Static Methods in Interfaces

Lochana Ranaweera
Lochness Writes
Published in
2 min readNov 20, 2015

Java 8 has several solutions to support evolution of interfaces. In the last post I explained about one such solution, default methods. Today I’ll be explaining another solution: static methods in Interfaces.

Static methods before Java 8:

Surely, you must’ve used the static keyword to create class members such as fields and methods. Also, it is known that static class members belong to the class, rather than to an instance of the class.

Invocation of a static method can be done with the class name as follows:

ClassName.methodName(args)

Tip: The creation of an instance of the class to invoke the static method through that instance is discouraged because then it does not make it clear that the method is a class method.

Before Java 8 made it possible to include static methods in interfaces, it was common to place static methods in companion utility classes. An example for a companion class — interface combination would be java.nio.file.Paths class and java.nio.file.Path interface. Class java.nio.file.Paths consists exclusively of static methods that return a Path by converting a path string or URI. One such method in this class is given below:

public static Path get(String first,String… more)

This method allows to construct a path from a sequence of strings. An example is given below.

Main.java

To use the Paths class and Path interface I have imported them as shown at the lines 3 and 4. Notice the Paths.get(“/home/lochana/Desktop/example.txt”) method call. It is the call to the Paths.get() method that creates the Path instance. In other words, Paths.get() method is a factory method for Path instances. I have created an absolute path by calling the Paths.get() method using an absolute file as the parameter.

Is it possible to put a static method in an Interface?

Instead of having the above get() method in the java.nio.file.Paths class, it would be more appropriate to include it in the relevant interface java.nio.file.Path. Now, with Java 8 you can do this!

Then the Paths class is no longer necessary, as we can use the Path interface alone to invoke the get() method.

What I have shown above is just an example. It is unlikely Java Paths library will be re-factored this way. However, when we implement our own interfaces it is no longer necessary to have a separate companion class to contain all the utility methods. Instead they can be contained as static methods in the interface itself, which would actually make more sense in usage.

--

--