Sub topic 13
Static Methods in Interfaces
So far, every method in an interface has belonged to the objects that implement it. An abstract method is a promise that each class must keep. A default method is a ready-made body that each object inherits. Since Java 8, an interface can also hold a third kind of method, the static method.
A static method is a method that belongs to a type itself, not to any object of that type. You already know static methods from classes, such as Math.max(3, 7). You never create a Math object. You just call the method on the name Math. Static methods in interfaces work the same way. You call them on the interface's name.
Why Put a Static Method in an Interface?
Before Java 8, interfaces could not hold static methods. Programmers who wanted helper code for an interface had to make a separate class to hold it. The Collection interface, for example, had a companion class called Collections that was full of static helpers. That split the code into two places, so readers had to know where to look.
A static method in the interface keeps the helper next to the type it helps. You will see two common uses:
- Factory methods. A factory method is a method whose job is to create and return an object. The caller gets an object of the interface type and does not need to know which class built it.
- Utility methods. A utility method is a small helper that works with objects of the interface type, such as adding up values from several of them.
Declaring and Calling a Static Method
To declare one, write static before the return type and give the method a body. A static interface method must have a body, because no class will ever supply one later.
Here is a Greeter interface with one abstract method and two static factory methods.
interface Greeter {
String greet(String name);
static Greeter polite() {
return new PoliteGreeter();
}
static Greeter casual() {
return new CasualGreeter();
}
}
class PoliteGreeter implements Greeter {
@Override
public String greet(String name) {
return "Good morning, " + name + ".";
}
}
class CasualGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hey " + name + "!";
}
}
public class Main {
public static void main(String[] args) {
Greeter g = Greeter.polite();
System.out.println(g.greet("Ana")); // prints: Good morning, Ana.
System.out.println(Greeter.casual().greet("Ben")); // prints: Hey Ben!
}
}Look at the call Greeter.polite(). It names the interface, then a dot, then the method. The code in main never mentions PoliteGreeter. It only knows it has a Greeter. This is programming to an abstract type: you could later swap in a different class inside polite(), and main would not change.
A Utility Method Example
Static methods are also handy for work that involves many objects at once. Here a Shape interface offers a static helper that adds up the areas of several shapes.
interface Shape {
double area();
static double totalArea(Shape... shapes) {
double total = 0;
for (Shape s : shapes) {
total += s.area();
}
return total;
}
}
class Rectangle implements Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Shape a = new Rectangle(2, 3);
Shape b = new Rectangle(4, 5);
System.out.println(Shape.totalArea(a, b)); // prints: 26.0
}
}The Shape... parameter is a varargs parameter: the method accepts any number of Shape values and sees them as an array. The helper calls area() on each one, so it works with every class that implements Shape.
The Big Rule: Static Methods Are Not Inherited
This is the part that surprises beginners most. A default method is inherited by every implementing class. A static interface method is not. It stays with the interface. You can reach it in only one way, through the interface's name.
interface Counter {
static int start() {
return 0;
}
}
class Clicker implements Counter {
}
public class Main {
public static void main(String[] args) {
System.out.println(Counter.start()); // works, prints: 0
// Clicker.start(); // compile error: not inherited by Clicker
// new Clicker().start(); // compile error: cannot call through an object
}
}Both commented lines fail to compile. This is different from static methods in classes. A subclass can call its parent class's static methods through its own name. Java's designers made interfaces stricter on purpose. A class can implement many interfaces, and two of them might have static methods with the same name. Because the methods are not inherited, they can never clash.
A static method also has no this. It does not run on any object, so it cannot call the interface's abstract or default methods directly. It can only call them on an object it is given, as totalArea does with s.area().
Comparing the Three Kinds of Interface Methods
| Kind | Has a body? | Inherited by implementing classes? | How you call it |
|---|---|---|---|
| Abstract | No | Yes, and the class must implement it | `object.method()` |
| Default | Yes | Yes, and the class may override it | `object.method()` |
| Static | Yes | No | `InterfaceName.method()` |
Static Methods in the Java Library
The Java library uses this feature in many places. List.of(...) builds a list that cannot be changed. Comparator.naturalOrder() returns a comparator that sorts values in their usual order.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Cleo", "Ana", "Ben"));
names.sort(Comparator.naturalOrder());
System.out.println(names); // prints: [Ana, Ben, Cleo]
}
}Both List and Comparator are interfaces. Their static methods give you useful objects without asking you to learn the names of the classes behind them.
Common Mistakes
- Leaving off the body.
static Greeter polite();does not compile. A static method must have a body. - Calling through the implementing class. Write
Greeter.polite(), notPoliteGreeter.polite(). - Calling through an object. Write
Shape.totalArea(a, b), nota.totalArea(a, b). - Expecting to override it. A static method with the same name in a class is a separate method. It does not change what the interface's method does.
Exercise
Given interface Timer { static Timer create() { return new BasicTimer(); } } and class BasicTimer implements Timer {}, which of these lines compile: (a) Timer t = Timer.create(); (b) Timer t = BasicTimer.create(); (c) Timer t = new BasicTimer().create();?
Show answer
Only (a) compiles. Static interface methods are not inherited, so BasicTimer does not have a create() method. That means (b) fails. You also cannot call a static interface method through an object, so (c) fails too.
Exercise
Add a static method max(Shape a, Shape b) to the Shape interface from this chapter. It should return whichever shape has the larger area. Then show how to call it from main.
Show answer
Inside Shape, add static Shape max(Shape a, Shape b) { return a.area() >= b.area() ? a : b; }. In main, call Shape bigger = Shape.max(new Rectangle(2, 3), new Rectangle(4, 5)); and then System.out.println(bigger.area()); prints 20.0.
Exercise
Why does Java refuse to let implementing classes inherit static interface methods, even though subclasses can use their parent class's static methods?
Show answer
A class can implement many interfaces, and two of them could declare static methods with the same signature. If those methods were inherited, the class would hold two clashing methods with no way to choose. Keeping static methods tied to the interface name means every call, such as A.helper() or B.helper(), says exactly which method it means.