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 lambda expression capability of Java 8.
For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such method will simply break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not implement the same.
Syntax
interface TwoWheeler {
default void print() {
System.out.println("I am a two wheeler!");
}
}
Multiple Defaults
With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved.
interface TwoWheeler {
default void print() {
System.out.println("I am a two wheeler!");
}
}
interface FourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
First solution is to create an own method that overrides the default implementation.
class Vehicle implements TwoWheeler, FourWheeler {
public void print() {
System.out.println("I am a vehicle!");
}
}
Second solution is to call the default method of the specified interface using super.
class Vehicle implements TwoWheeler, FourWheeler {
public void print() {
TwoWheeler.super.print();
}
}
Static Default Methods
An interface can also have static helper methods from Java 8 onwards.
interface TwoWheeler {
default void print() {
System.out.println("I am a two wheeler!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
Default Method Example
Create the following Java program using any editor of your choice in, say, C:\hitechpoints\workspace\java8\src>.
Java8Feature.java
public class Java8Feature {
public static void main(String args[]) {
TwoWheeler twoWheeler = new Vehicle();
// Calling vehicle's print method
twoWheeler.print();
}
}
interface TwoWheeler {
default void print() {
System.out.println("I am a two wheeler!");
}
static void blowHorn() {
System.out.println("Blowing horn!!!");
}
}
interface FourWheeler {
default void print() {
System.out.println("I am a four wheeler!");
}
}
class Vehicle implements TwoWheeler, FourWheeler {
public void print() {
TwoWheeler.super.print();
FourWheeler.super.print();
TwoWheeler.blowHorn();
System.out.println("I am a Vehicle!");
}
}
Output
Compile the class using javac compiler as follows –
C:\hitechpoints\workspace\java8\src>javac Java8Feature.java
Now run the Java8Feature r as follows –
C:\hitechpoints\workspace\java8\src>java Java8Feature
It should produce the following output –
I am a two wheeler! I am a four wheeler! Blowing horn!!! I am a Vehicle!