Monday, 28 July 2014

Default Methods: Java 8's Unsung Heros

A few weeks ago I wrote a blog saying that developers learn new languages because they're cool. I still stand by this assertion because the thing about Java 8 is it's really cool. Whilst the undoubted star of the show is the addition of Lambdas and the promotion of functions to first class variables, my current favourite is default methods. This is because they're such a neat way of adding new functionality to existing interfaces without breaking old code.

The implementation is simple: take an interface, add a concrete method and attach the keyword default as a modifier. The result is that suddenly all existing implementations of your interface can use this code. In this first, simple example, I’ve added default method that returns the version number of an interface1.

public interface Version {

 
/**
   * Normal method - any old interface method:
   *
   *
@return Return the implementing class's version
   */
 
public String version();

 
/**
   * Default method example.
   *
   *
@return Return the version of this interface
   */
 
default String interfaceVersion() {
   
return "1.0";
 
}

}

You can then call this method on any implementing class.