Java 8 Interface Default Methods example

15 May 2014
By Gonçalo Marques
In this article we will cover Java 8 interface default methods.

Java 8 Interface Default Methods

One of the new features introduced in Java 8 consists in interface default methods, also know as Extension Methods.

Interfaces now may also provide default method implementations:

TestInterface.java

package com.byteslounge;

public interface TestInterface {

  default String methodOne(String input){
    return "Default methodOne implementation. Input: " + input;
  }
  
  String methodTwo(String input);
  
}

As we can see above, TestInterface is providing a default implementation for method methodOne.

This means that any concrete class that directly implements TestInterface is not required to implement method methodOne:

TestClass.java

package com.byteslounge;

public class TestClass implements TestInterface {

  @Override
  public String methodTwo(String input) {
    return "methodTwo implementation. Input: " + input;
  }

}

If methodOne is called against a TestClass instance, the default method defined in TestInterface will be called.

We are obviously still able to override methodOne if we need it:

TestClass.java

package com.byteslounge;

public class TestClass implements TestInterface {

  @Override
  public String methodTwo(String input) {
    return "methodTwo implementation. Input: " + input;
  }

  @Override
  public String methodOne(String s) {
    return "methodOne is overriden!";
  }

}

Related Articles

Comments

About the author
Gonçalo Marques is a Software Engineer with several years of experience in software development and architecture definition. During this period his main focus was delivering software solutions in banking, telecommunications and governmental areas. He created the Bytes Lounge website with one ultimate goal: share his knowledge with the software development community. His main area of expertise is Java and open source.

GitHub profile: http://github.com/gonmarques

He is also the author of the WiFi File Browser Android application: