CodeGym /Courses /JAVA 25 SELF /Static methods in interfaces

Static methods in interfaces

JAVA 25 SELF
Level 21 , Lesson 3
Available

1. Introduction

Before Java 8, an interface was strictly a “contract”: only abstract methods, no implementation, no logic — just promises. But starting with Java 8, interfaces became a bit more “self-sufficient”: they can now contain not only default methods but also static methods.

Static methods in interfaces are methods that belong to the interface itself rather than its implementations (classes). They do not require creating an object and are called directly via the interface name.

Analogy:
Static methods in interfaces are like a cheat sheet posted on the office wall: every employee (class) can use it, but the cheat sheet does not belong to any one employee.

Static methods in interfaces let you group helper functions related to that interface without cluttering the namespaces of implementing classes.

Syntax of static methods in interfaces

Static methods are declared inside an interface using the static keyword. They can contain an implementation (code inside curly braces) and can only be called via the interface name.

Example:

public interface MathUtils {
    static int sum(int a, int b) {
        return a + b;
    }

    static double average(int a, int b) {
        return (a + b) / 2.0;
    }
}

Calling a static interface method:

int result = MathUtils.sum(5, 7);        // 12
double avg = MathUtils.average(10, 20);  // 15.0

Important:
You cannot call an interface’s static method via an implementing class or an object! Only via the interface name.

2. How do interface static methods differ from default methods?

Static methods:

  • Belong to the interface itself.
  • Are not inherited by implementing classes.
  • Cannot be called via a class’s object.
  • Cannot be overridden in an implementing class.
  • Can be called only via the interface name.

default methods:

  • Belong to the object (instance) of the class implementing the interface.
  • Can be overridden in the implementing class.
  • Can be called via an object of the implementing class.
  • Are inherited by implementing classes.

In short: default methods extend the capabilities of the object, while static methods extend the interface itself.

Comparison example:

interface Printer {
    default void print(String text) {
        System.out.println("Default: " + text);
    }

    static void info() {
        System.out.println("Printer interface v1.0");
    }
}

class ConsolePrinter implements Printer {}

public class Main {
    public static void main(String[] args) {
        Printer.info(); // Call a static method via the interface

        ConsolePrinter cp = new ConsolePrinter();
        cp.print("Hello!"); // Call a default method via the object
        // cp.info(); // Error! You cannot call a static method via an object
    }
}

3. Why do we need static methods in interfaces?

Before static methods in interfaces existed, if you needed to add a utility function related to an interface, you had to create separate classes with the Utils or Helper suffix:

public interface Movable {
    void move(int x, int y);
}

public class MovableUtils {
    public static void resetPosition(Movable m) {
        m.move(0, 0);
    }
}

Now you can do it right in the interface:

public interface Movable {
    void move(int x, int y);

    static void resetPosition(Movable m) {
        m.move(0, 0);
    }
}

This makes the code more logical and cohesive: methods related to the interface now live right inside it.

Advantages:

  • Group utility functions next to the interface contract.
  • Do not clutter the namespaces of implementing classes.
  • Improve readability and maintainability.

4. Limitations and specifics of interface static methods

Interface static methods are not inherited by implementing classes.

They cannot be called via an object of an implementing class or via the class name. Only via the interface name!

Static methods in an interface always have an implementation: they cannot be abstract or default.

They always contain an implementation.

Static methods cannot access non-static methods or variables of the interface.

They can access only other static members of the interface (for example, static final constants).

Interface static methods can be private (Java 9+).

You can create helper private static methods for internal use within the interface.

5. Example: static methods for the Movable interface

Let’s see how to add static methods to the Movable interface. Suppose we have a Movable interface implemented by different classes (e.g., robots, animals, vehicles).

Step 1. Declare the interface with a static method:

public interface Movable {
    void move(int x, int y);

    static void resetPosition(Movable obj) {
        obj.move(0, 0);
    }

    static double distance(int x1, int y1, int x2, int y2) {
        int dx = x2 - x1;
        int dy = y2 - y1;
        return Math.sqrt(dx * dx + dy * dy);
    }
}

Step 2. Implement the interface in a class:

public class Robot implements Movable {
    private int x, y;

    public Robot(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void move(int x, int y) {
        System.out.println("Robot moves to point (" + x + "," + y + ")");
        this.x = x;
        this.y = y;
    }

    public void printPosition() {
        System.out.println("Current position: (" + x + "," + y + ")");
    }
}

Step 3. Use the interface’s static methods:

public class Main {
    public static void main(String[] args) {
        Robot robby = new Robot(10, 15);
        robby.printPosition();

        // Reset position via the interface's static method
        Movable.resetPosition(robby);
        robby.printPosition();

        // Compute distance between points via the interface's static method
        double dist = Movable.distance(0, 0, 10, 15);
        System.out.println("Distance: " + dist);
    }
}

Result:

Current position: (10,15)
Robot moves to point (0,0)
Current position: (0,0)
Distance: 18.027756377319946

Note:
We call Movable.resetPosition(robby), not robby.resetPosition(). Static methods are convenient for operations that logically relate to the interface but not to a specific object.

6. Private static methods in interfaces

Sometimes you need helper methods in an interface for internal needs only (e.g., to avoid duplicating code in several static or default methods). Since Java 9, interfaces support private static methods.

Example:

public interface Logger {
    static void logInfo(String message) {
        log("INFO", message);
    }
    static void logError(String message) {
        log("ERROR", message);
    }
    private static void log(String level, String message) {
        System.out.println("[" + level + "] " + message);
    }
}

Now log() is not accessible from outside the interface, but it is used inside other static methods.

7. Where are static methods in the Java standard library?

Static methods in interfaces are actively used in the Java standard library, especially in collections and functional interfaces.

Examples:

  • Comparator.comparing(), Comparator.reverseOrder() — static methods of the Comparator interface.
  • Predicate.isEqual() — a static method of the Predicate interface.
  • List.of(), Set.of(), Map.of() (Java 9+) — static methods for creating immutable collections.

Example with Comparator:

import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        Comparator<String> cmp = Comparator.reverseOrder();
        int res = cmp.compare("a", "b"); // a positive number because "a" > "b" in reverse order
        System.out.println(res);
    }
}

8. Common mistakes when working with interface static methods

Mistake #1: trying to call a static method via an object of the implementing class.
This will not work! An interface’s static method is called only via the interface name, for example, Movable.resetPosition(obj), not obj.resetPosition().

Mistake #2: trying to override an interface static method in an implementing class.
Static methods are not inherited and are not overridden! If you declare a static method with the same name in the class, it will be a completely different method unrelated to the interface.

Mistake #3: forgetting that static methods cannot access non-static members.
Interface static methods can use only static members (for example, static final constants) and cannot access non-static methods or variables.

Mistake #4: confusing default methods with static methods.
default methods are called via an object, while static methods are called only via the interface name. Don’t mix them up!

1
Task
JAVA 25 SELF, level 21, lesson 3
Locked
Required form fields check 📄
Required form fields check 📄
1
Task
JAVA 25 SELF, level 21, lesson 3
Locked
Universal Greeting System 🌐
Universal Greeting System 🌐
1
Task
JAVA 25 SELF, level 21, lesson 3
Locked
Mathematical Assistant for an Engineer 📐
Mathematical Assistant for an Engineer 📐
1
Task
JAVA 25 SELF, level 21, lesson 3
Locked
Centralized Logging System 🛡️
Centralized Logging System 🛡️
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION