Tuesday, 10 June 2025

static methods in interfaces

 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.


1. Declaration & Syntax

public interface Formatter {
    // A static method inside an interface
    static String format(String s) {
        return "s.trim().toUpperCase() ";
    }
}

Keyword: 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.

interface A {
    static void foo() { System.out.println("A.foo"); }
}

class C implements A {
    // You cannot do:
    // public static void foo() { ... }   // this is a new method, not an override
}

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 on List 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 {

    static Object parse(String json) {
        if (isBlank(json)) throw new IllegalArgumentException();
        // … parsing logic …
        return new Object();
    }

    private static boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }
}

Use Cases:

  • Utility/helper methods related to the interface (e.g., Comparator.comparing()).

  • Factory methods inside interfaces.

  • Constants processing, parsing, formatting, etc.


No comments:

Post a Comment