Both static methods and default methods were introduced in interfaces to enhance functionality without breaking existing implementations. However, they serve different purposes. A static method belongs to the interface itself, while a default method provides a reusable implementation that can be inherited and overridden by implementing classes.
Key Points: • Static methods belong to the interface and are called using the interface name. • Default methods provide a method implementation that implementing classes automatically inherit. • Static methods cannot be overridden by implementing classes. • Default methods can be overridden to provide custom behavior. • Static methods are commonly used for utility or helper functions. • Default methods help add new functionality to interfaces without affecting existing implementations.
Example: Consider a Payment interface. A static method can validate payment details, while a default method can provide a common payment status message.
Code Example:
interface Payment {
static boolean isValidAmount(double amount) {
return amount > 0;
}
default void showStatus() {
System.out.println("Payment Processed");
}
}
class UpiPayment implements Payment {
@Override
public void showStatus() {
System.out.println("UPI Payment Processed");
}
}
public class Demo {
public static void main(String[] args) {
System.out.println(
Payment.isValidAmount(1000)
);
UpiPayment payment = new UpiPayment();
payment.showStatus();
}
}Output:
true UPI Payment Processed
Comparison:
Static Method: • Belongs to the interface • Called using InterfaceName.method() • Cannot be overridden • Used for utility/helper functionality
Default Method: • Inherited by implementing classes • Called using object reference • Can be overridden • Used to provide default behavior
Common Use Cases:
Static Method: • Validation logic • Utility methods • Factory methods
Default Method: • Shared business logic • Backward compatibility • Common implementation for all implementing classes
Interview Tip: A concise interview answer is:
"A static method in an interface belongs to the interface itself and is called using the interface name. It cannot be overridden. A default method provides a concrete implementation that implementing classes inherit and may override if needed. Static methods are used for utility functions, while default methods provide shared behavior."