All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Java › Interfaces & Abstract Classes

What are static methods on an interface, and how do they differ from default methods in terms of inheritance and typical use case?

Intermediate

Answer

A static method on an interface (also introduced in Java 8) belongs to the interface itself, not to any implementing class, meaning it's called via InterfaceName.staticMethod() and is NOT inherited by implementing classes at all (unlike a default method, which every implementing class does inherit) -- interface static methods are commonly used for utility/helper methods closely related to the interface's purpose (like factory methods creating instances of the interface, or common validation logic used across multiple default methods), keeping such utility code directly co-located with the interface it serves rather than requiring a separate, unrelated utility class.
public interface Comparator<T> {
    int compare(T a, T b);

    static <T extends Comparable<T>> Comparator<T> naturalOrder() {  // static factory method
        return Comparable::compareTo;
    }
}

Comparator<String> cmp = Comparator.naturalOrder();  // called via the interface name, NOT inherited by implementers
// cmp.naturalOrder() would NOT work if cmp were some implementing class instance -- it's not inherited
Real-world example The JDK's Comparator interface provides several static factory methods (naturalOrder(), reverseOrder(), comparing()) directly on the interface itself, providing convenient, discoverable ways to construct common Comparator instances without needing a separate ComparatorFactory utility class disconnected from the interface it actually relates to.

Common follow-ups: Why doesn't a static interface method get inherited by implementing classes, unlike a default method?;What access modifier can interface static methods have, and has this changed across Java versions?