Java.Java8.What is a static method of an interface?

✅ What Is a Static Method in an Interface?

A static method in an interface is a method that:

  • Belongs to the interface itself, not to the implementing class
  • Cannot be overridden
  • Can be used to define utility or helper methods related to that interface

Static

interface MathUtils {
    static int square(int x) {
        return x * x;
    }
}

✅ Calling the static method:

int result = MathUtils.square(5);
System.out.println(result); // Output: 25

🟡 Note: You must call it via the interface name, not via an instance.

🚫 You cannot do this:

class Calculator implements MathUtils {
    void use() {
        square(5); // ❌ Compile-time error!
    }
}

✅ You must do this:

MathUtils.square(5); // ✅

✅ Why Use Static Methods in Interfaces?

ReasonBenefit
📦 Utility logic groupingGroup helper methods with interface definitions
🚫 Prevent overridingKeeps logic consistent and unchangeable in implementations
📘 API design clarityImproves readability and maintainability

🧠 Real-World Example: Java’s Comparator

Comparator<String> byLength = Comparator.comparingInt(String::length);

➡️ Comparator.comparingInt(...) is a static method in the Comparator interface.

You can’t do:

byLength.comparingInt(...); // ❌ Doesn't compile

You must do:

Comparator.comparingInt(...); // ✅

✅ Summary

FeatureStatic Methods in Interfaces
📌 Belongs toInterface itself (not to implementing class)
🚫 Cannot be overriddenTrue
📞 Call syntaxInterfaceName.methodName(...)
✅ Use caseUtility methods tied to the interface
Introduced inJava 8
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.