In Java 8, the default
method is a feature introduced in interfaces to allow adding new methods to interfaces without breaking existing implementations.
✅ Definition: A default method in an interface provides a method with a body, using the default
keyword.
public interface Vehicle {
void start();
default void horn() {
System.out.println("Default horn sound!");
}
}
✅ Why Introduced?
Before Java 8, interfaces could only have abstract methods. Adding a new method to an interface would break all implementing classes.
Default methods solve this by allowing a method implementation inside the interface.
public interface Vehicle {
void start();
default void horn() {
System.out.println("Beep beep!");
}
}
public class Car implements Vehicle {
public void start() {
System.out.println("Car started.");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Output: Car started.
car.horn(); // Output: Beep beep!
}
}
✅ Key Points
Feature | Description |
---|---|
Keyword | default keyword used inside interface |
Inheritance | Classes can override default methods |
Multiple Inheritance Issue | Handled by compiler with rules |
Conflict Rule (Diamond Problem)
If a class implements two interfaces with same default method, the class must override it:
interface A {
default void show() {
System.out.println("A");
}
}
interface B {
default void show() {
System.out.println("B");
}
}
class C implements A, B {
// Must override show() to resolve conflict
public void show() {
System.out.println("C");
}
public static void main(String[] args) {
C obj = new C();
obj.show(); // Output: C
}
}
Optionally, if you want to call a specific interface's default method inside the override:
class C implements A, B {
public void show() {
A.super.show(); // or B.super.show();
}
public static void main(String[] args) {
C obj = new C();
obj.show(); // Output: A
}
}