✅ 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?
Reason | Benefit |
---|---|
📦 Utility logic grouping | Group helper methods with interface definitions |
🚫 Prevent overriding | Keeps logic consistent and unchangeable in implementations |
📘 API design clarity | Improves 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
Feature | Static Methods in Interfaces |
---|---|
📌 Belongs to | Interface itself (not to implementing class) |
🚫 Cannot be overridden | True |
📞 Call syntax | InterfaceName.methodName(...) |
✅ Use case | Utility methods tied to the interface |
Introduced in | Java 8 |