Definition:
In Java 8, interfaces can contain static methods
, which are methods that:
-
Have a body (implementation).
-
Belong to the interface itself, not to the implementing classes.
-
Can be called only using the interface name.
Static methods in interfaces cannot be inherited or overridden by implementing classes.
static
Body: Must provide an implementation.
No access modifier: They’re implicitly public
, but you can write public static
if you like.
2. Invocation
You cannot call a static interface method on an instance or from an implementing class. Always call it on the interface name:
public class TestFormatter {
public static void main(String[] args) {
String raw = " hello world ";
// Correct:
String formatted = Formatter.format(raw);
System.out.println(formatted); // Outputs: HELLO WORLD
// Incorrect (won’t compile):
// FormatterImpl impl = new FormatterImpl();
// impl.format(raw);
}
}
3. Overriding & Inheritance
-
Cannot be overridden in implementing classes or subinterfaces.
-
They do not participate in the class’s inheritance hierarchy.
4. Common Use-Cases
-
Utility methods related to the interface’s concept.
-
e.g.
Comparator.nullsFirst(…)
,Comparator.comparing(…)
-
e.g. factory methods like
List.of(…)
in Java 9+, though that’s onList
interface.
-
-
Validation or pre-/post-processing helpers for interface implementations.
5. Java 9+ Enhancements
Since Java 9, interfaces can also contain private static methods (and private instance methods) to share code between other interface methods: e.g.,
public interface Parser {
Use Cases:
-
Utility/helper methods related to the interface (e.g.,
Comparator.comparing()
). -
Factory methods inside interfaces.
-
Constants processing, parsing, formatting, etc.