Default & Static Methods in Interfaces (Java 8+)
1Concept
Java 8 introduced `default` methods in interfaces to enable backward compatibility for evolving APIs (e.g. adding `.stream()` to `Collection` without breaking millions of third-party libraries). Static methods in interfaces serve as utility helper functions scoped directly to the interface.
2Architecture Diagram
Interface: default void logAudit() { ... } ---> Subclass can use as-is OR override
Interface: static Order empty() { ... } ---> Invoked via InterfaceName.empty()3Code Example
Core Java
public class InterfaceDefaultStaticDemo {
interface PaymentProcessor {
void executePayment(double amount);
// Default method: provides optional default behavior
default void sendReceipt(String email, double amount) {
System.out.println("Receipt sent to " + email + " for $" + amount);
}
// Static helper method
static boolean isValidCurrency(String code) {
return code != null && (code.equals("USD") || code.equals("EUR"));
}
}
static class StripeProcessor implements PaymentProcessor {
@Override
public void executePayment(double amount) {
System.out.println("Stripe processed charge: $" + amount);
}
}
public static void main(String[] args) {
PaymentProcessor processor = new StripeProcessor();
processor.executePayment(199.99);
processor.sendReceipt("client@corp.com", 199.99); // Invokes default method
System.out.println("Is USD valid: " + PaymentProcessor.isValidCurrency("USD"));
}
}4Expected Output
Stripe processed charge: $199.99 Receipt sent to client@corp.com for $199.99 Is USD valid: true
5Key Takeaways
- ✓Default methods cannot override methods of java.lang.Object (equals, hashCode, toString).
- ✓Classes always win: if a superclass and interface have identical methods, superclass implementation takes priority.
- ✓Static interface methods are NOT inherited by implementing classes.