Saturday, November 18, 2017

Java 9 - Private methods in Interface

Prior to Java 8, Java Interfaces can contain method signatures but without any implementation.

In Java 8, default methods were introduced where we can add new methods and a default implementation for the same. Though it was originally intended to allow people to add new interface methods without requiring all implementations to change (by providing a default implementation), we are using default methods in many different ways which may or may not be how it was originally intended to be used. If you have multiple default method implementations in an interface, we may end up having duplicate code due to lack of private methods.

Some options available to do this 
  • Another default method with common logic.
  • An external class containing Utility methods.
Both cases expose the implementation details to outside classes which otherwise supposed to be a private to default methods.

In Java 9, we can now create private methods in an interface which are to be used by default methods. 

So, if we have default methods in an interface and need to share a particular logic, a private interface method would allow us to do so without exposing that private method and all its implementation details via the interface (or a Utility class).

Have a look at an interesting enhancement in Java 9 - Try-with-resource enahancement

No comments: