Java Interface – Journey Over the Years to Java 9 – Default and Private Methods

Introduction

Interface in Java has evolved over the Java releases more so in Java 8 and Java 9. In this article we will look at how Interface was prior to Java 8 and how it has been enhanced in Java 8 and Java 9

Interface prior to Java 8

An interface would have one or more abstract methods as shown below:

public interface MyInterface {
  public void doSomething();
}

And its implementation would be:

public class MyImplementation implements MyInterface{

  public void doSomething() {
    System.out.println("Done in MyImplementation");
  }

  public static void main(String[] args) {
    MyImplementation impl = new MyImplementation();
    impl.doSomething();
  }

}

Interface in Java 8

In Java 8, in order to enhance the collections API to support lambda expressions and new methods the interface java.util.Collection had to be enhanced. This would mean breaking all that code which was implementing this interface. So they came up with something called default methods in the interface.

So now interfaces could have methods with implementations and thereby providing a scope for the enhancement of the interfaces:

public interface MyInterface {
  public void doSomething();

  public default void doTheDefaultThing() {
    System.out.println("Done in a default way!");
  }
}

Interface in Java 9

Even after the default methods, there was a small limitation in the interface which was the lack of constructs for sharing the code between the default methods.
In Java 9, they introduced private methods which facilitate for code sharing between the non-abstract methods in the interface:

public interface MyInterface {
  public void doSomething();

  public default void doTheDefaultThing() {
    System.out.println("Done in a default way!");
    helper();
  }

  private void helper() {
    System.out.println("Calling the helper!!!");
  }
}

And the above interface enhancements in action:

public static void main(String[] args) {
  MyImplementation impl = new MyImplementation();
  impl.doSomething();
  impl.doTheDefaultThing();
}

Conclusion

The JDK team has clearly made the interfaces much more powerful than they were prior to Java8 and also opened up a way to enhance the interfaces in the libraries without breaking client’s code.

Leave a Reply

%d bloggers like this: