logo

Default Methods


Show

Java 8 introduces a replacement concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces are often wont to leverage the lambda expression capability of Java 8.

For example, ‘List’ or ‘Collection’ interfaces don't have the ‘forEach’ method declaration. Thus, adding such a method will simply break the gathering framework implementations. Java 8 introduces a default method so that the List/Collection interface can have a default implementation of the forEach method, and therefore the class implementing these interfaces needn't implement an equivalent.

Syntax

public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
}

Multiple Defaults

In default functions in interfaces, there is an opportunity in the category of implementing two interfaces with the same default methods. The subsequent code explains how this ambiguity is often resolved.

public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
}

public interface fourWheeler {

   default void print() {
      System.out.println("I am a four wheeler!");
   }
}

The first solution is to create an own method that overrules the default enactment

public class car implements vehicle, fourWheeler {

   public void print() {
      System.out.println("I am a four wheeler car vehicle!");
   }
}

Secondly, you can also use call the default method of the state interface using super.

public class car implements vehicle, fourWheeler {

   public void print() {
      vehicle.super.print();
   }
}

Default Static Method

The defaulter also has static helper methods beyond Java 8.

 public interface vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}

Example of Default Method

You can create the given java program by using any editor of your choice in, say, C:\> JAVA.

Java8Tester.java

public class Java8Tester {

   public static void main(String args[]) {
      Vehicle vehicle = new Car();
      vehicle.print();
   }
}


interface Vehicle {

   default void print() {
      System.out.println("I am a vehicle!");
   }
   static void blowHorn() {
      System.out.println("Blowing horn!!!");
   }
}

interface FourWheeler {

   default void print() {
      System.out.println("I am a four wheeler!");
   }
}

class Car implements Vehicle, FourWheeler {

   public void print() {
      Vehicle.super.print();
      FourWheeler.super.print();
      Vehicle.blowHorn();
      System.out.println("I am a car!");
   }
}

Check your Result:

Assemble the class using javac compiler same as given below:

C:\JAVA>javac Java8Tester.java

Now you have to run the Java8Tester as given:

C:\JAVA>java Java8Tester

Your outcome should be like this:

I am a vehicle!
I am a four wheeler!
Blowing horn!!!
I am a car!