Default Methods for Interfaces

Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the default keyword. This feature is also known as virtual extension methods.

Here is our first example:

  1. interfaceFormula{
  2. double calculate(int a);
  3. defaultdouble sqrt(int a){
  4. returnMath.sqrt(a);
  5. }
  6. }

Besides the abstract method calculate the interface Formula also defines the default method sqrt. Concrete classes only have to implement the abstract method calculate. The default method sqrt can be used out of the box.

  1. Formula formula =newFormula(){
  2. @Override
  3. publicdouble calculate(int a){
  4. return sqrt(a *100);
  5. }
  6. };
  7. formula.calculate(100);// 100.0
  8. formula.sqrt(16);// 4.0

The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation of sqrt(a * 100). As we’ll see in the next section, there’s a much nicer way of implementing single method objects in Java 8.