Default methods were introduced in Java 8 to allow interfaces to evolve without breaking existing implementations. They enable developers to add new methods with a default implementation directly into an interface, ensuring that classes already implementing the interface continue to work without requiring code changes.
Key Points: • Default methods help maintain backward compatibility by allowing new functionality to be added to interfaces without affecting existing implementations. • Existing classes automatically inherit the default implementation if they do not provide their own version of the method. • They make API evolution easier, especially for large frameworks and libraries that are used by many applications.
Example: Suppose a PaymentProcessor interface is already implemented by hundreds of classes. If a new method is added as a default method, all existing implementations continue to compile and run without modification, while new implementations can override the method if needed.
Code Example:
interface PaymentProcessor {
void processPayment();
default void generateReceipt() {
System.out.println(
"Generating Receipt");
}
}
class CreditCardPayment
implements PaymentProcessor {
@Override
public void processPayment() {
System.out.println(
"Processing Payment");
}
}
public class Main {
public static void main(String[] args) {
PaymentProcessor payment =
new CreditCardPayment();
payment.processPayment();
payment.generateReceipt();
}
}Interview Tip: A concise interview answer is: Default methods improve backward compatibility by allowing new methods to be added to interfaces with a default implementation. Existing classes do not need to implement the new methods, which prevents breaking changes and simplifies API evolution.