Default methods introduced in Java 8 allow interfaces to contain method implementations, making it possible to enhance existing interfaces without forcing all implementing classes to change. This feature significantly improved API evolution by enabling new functionality to be added while maintaining backward compatibility.
Key Points: • Default methods allow interfaces to evolve without breaking existing implementations, improving backward compatibility. • They promote code reuse by providing common behavior directly within interfaces, reducing the need for utility classes. • Interfaces become more powerful and flexible, supporting multiple inheritance of behavior while still defining contracts.
Example: Suppose a PaymentService interface is used by hundreds of applications. If a new logging feature needs to be added, a default method can provide the implementation without requiring every existing PaymentService implementation to be modified.
Code Example:
interface PaymentService {
void processPayment();
default void logTransaction() {
System.out.println("Transaction Logged");
}
}
class UpiPayment implements PaymentService {
@Override
public void processPayment() {
System.out.println("UPI Payment Processed");
}
}
public class Main {
public static void main(String[] args) {
PaymentService payment = new UpiPayment();
payment.processPayment();
payment.logTransaction();
}
}Interview Tip: A concise interview answer is: Default methods enable interfaces to add new functionality without breaking existing implementations. They improve backward compatibility, support code reuse, and make it easier to evolve APIs while preserving existing application behavior.