Java 8 introduced default methods to allow interfaces to contain methods with predefined implementations. This feature makes it easier to extend existing interfaces without forcing all implementing classes to add the new method.
- A default method is declared using the default keyword and contains a method body.
- An implementing class inherits the default implementation unless it overrides the method.
- When two interfaces provide the same default method, the implementing class must resolve the conflict.
Example: In this program, the GFG class uses the default service() method provided by the Vehicle interface.
interface Vehicle {
void start();
default void service() {
System.out.println("Vehicle service is required");
}
}
public class GFG implements Vehicle {
@Override
public void start() {
System.out.println("Vehicle started");
}
public static void main(String[] args) {
GFG obj = new GFG();
obj.start();
obj.service();
}
}
Output
Vehicle started Vehicle service is required
Explanation: Since service() already has an implementation, GFG uses it directly without overriding the method.
Syntax
default returnType methodName(){
// implementation
}
Resolving Default Method Conflicts
When multiple interfaces provide default methods with the same signature, Java requires the implementing class to resolve the conflict by overriding the method or explicitly selecting a specific interface implementation.
1. Default Method Conflict
A conflict occurs when a class implements two interfaces that contain default methods with the same name and signature. The class must override the method to provide its own implementation.
interface Printer {
default void print() {
System.out.println("Printing from Printer");
}
}
interface Scanner {
default void print() {
System.out.println("Printing from Scanner");
}
}
public class GFG implements Printer, Scanner {
@Override
public void print() {
System.out.println("Custom print method");
}
public static void main(String[] args) {
GFG obj = new GFG();
obj.print();
}
}
Output
Custom print method
Explanation: Since both interfaces define print(), the class resolves the ambiguity by overriding the method.
2. Calling a Specific Default Method
A class that overrides a conflicting default method may also call a particular interface's implementation using the InterfaceName.super.methodName() syntax.
interface Printer {
default void print() {
System.out.println("Printer interface");
}
}
interface Scanner {
default void print() {
System.out.println("Scanner interface");
}
}
public class GFG implements Printer, Scanner {
@Override
public void print() {
Printer.super.print();
Scanner.super.print();
}
public static void main(String[] args) {
GFG obj = new GFG();
obj.print();
}
}
Output
Printer interface Scanner interface
Explanation: Printer.super.print() and Scanner.super.print() select the required interface implementations.