Java 8 introduces a new concept of default method implementation in interfaces.
This capability is added for backward compatibility so that old interfaces can be used to leverage the new features of Java 8.
For example, 'Collection’ interfaces do not have ‘forEach’ method declaration before java8.
Thus, adding such method will simply break the collection framework and all implementing clasees have to implement this method explicitly, otherwise it will lead to compile time errors.
So Java 8 introduces default method so that 'Collection' interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
Syntax:-
default void print() {
System.out.println("I am a vehicle!");
}
}
Multiple Defaults :-
With default functions in interfaces, there is a possibility that a class is implementing two interfaces having same default methods. The following code explains how this ambiguity can be resolved.
default void print() {
System.out.println("I am a vehicle!");
}
}
default void print() {
System.out.println("I am a four wheeler!");
}
}
Solutions:-
1. First solution is to create an own method that overrides the default implementation.
public void print() {
System.out.println("I am a four wheeler car vehicle!");
}
}
2. Second solution is to call the default method of the specified interface using super.
public void print() {
vehicle.super.print();
}
}
Static Default Methods:-
An interface can also have static helper methods from Java 8 onwards.
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
public static void main(String args[]) {
Vehicle vehicle = new Car();
vehicle.print();
}
}
default void print() {
System.out.println("I am a vehicle!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
default void print() {
System.out.println("I am a four wheeler!");
}
}
public void print() {
Vehicle.super.print();
FourWheeler.super.print();
Vehicle.blowHorn();
System.out.println("I am a car!");
}
}
Output:-
I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!