Java.Java8.How do I call a static method of an interface?

✅ Syntax:

You must call it using the interface name, not an object or implementing class.

InterfaceName.methodName(args);

🧠 Example:

interface Utils {
    static void printHello() {
        System.out.println("Hello from interface!");
    }
}

✅ Calling the static method:

public class Demo {
    public static void main(String[] args) {
        Utils.printHello(); // ✅ Correct
    }
}

❌ You cannot call it through an instance:

class MyClass implements Utils {}

MyClass obj = new MyClass();
obj.printHello(); // ❌ Compile-time error

Even though MyClass implements Utils, static methods do not get inherited.
They belong to the interface itself, not to the implementing class.

🔍 Real-World Example: Java’s Comparator

Comparator<String> c = Comparator.comparingInt(String::length); // ✅

int result = Comparator.naturalOrder().compare("a", "b"); // ✅

Comparator.naturalOrder(); // static method in interface

✅ Summary

Want to do…Correct Syntax
Call static method in interfaceInterfaceName.methodName()
Call via implementing class/obj❌ Not allowed
Override static method❌ Not possible
This entry was posted in Без рубрики. Bookmark the permalink.