Default methods are methods in an interface that provide a body using the default keyword, allowing implementing classes to inherit a working implementation instead of being forced to override it.
Key Points: • They were introduced primarily to let the JDK add new methods to existing interfaces, like Collection.stream() and List.sort(), without breaking every existing implementation. • A class implementing the interface automatically gets the default implementation unless it explicitly overrides the method. • If a class implements two interfaces with conflicting default methods, it must override the method to resolve the ambiguity, or the code fails to compile. • Default methods can be called via super in the implementing class, e.g. InterfaceName.super.methodName(), to invoke the interface's own version. • They blur the traditional line between interfaces and abstract classes, though interfaces still cannot hold instance state.
Example: The Comparator interface added a default method reversed() in Java 8, so any existing Comparator implementation automatically gained that capability without needing to be rewritten.
Code Example:
interface Vehicle {
void drive();
default void honk() {
System.out.println("Beep beep!");
}
}
class Car implements Vehicle {
public void drive() {
System.out.println("Driving...");
}
}
// new Car().honk(); prints "Beep beep!" without Car defining itInterview Tip: A concise interview answer is:
"Default methods let an interface provide a method body using the default keyword, so implementing classes get it for free. They were introduced so the JDK could add new methods to interfaces like Collection and Comparator without breaking every class that already implemented them — that's what made Streams possible to bolt onto the existing Collections Framework."