Private Interface Methods In Java 9

This quick tutorial is going to cover about private interface methods in Java 9.

1. Overview

As you may know, from Java 8, interfaces can have default methods which enable us to add new functionality to the interfaces of our libraries without breaking all classes that implement those changed interfaces, and therefore ensure binary compatibility with code written for older versions of those interfaces.

One possible problem when we work with the default methods in interfaces is the code reuse. Assume that our interface has two default methods and some of their parts have the same business logic. To prevent duplication of source code, we might put the code implemented for the same business logic into another common default method which can be reused by those methods. However, because all methods in an interface are public by default, that common method will be public too and is required to be implemented by all classes implement the interface. That was not our intention.

Fortunately, private interface methods are now supported in Java 9. This support allows nonabstract
methods of an interface to share code between them. So, for the above case, we can define the common default method as a private method which will not be public anymore, and therefore the problem is solved.

Next, let’s come with some examples of private interface methods in Java 9.

2. Example Of Private Interface Methods In Java 9

Let’s see a DrivingCar interface into which will be added two more public methods: turnLeft() and turnRight() as below:

Those two methods require the car to check for any obstacles before turning, they share the same source code for obstacle checking. As the private interface methods are now supported in Java 9, we now can encapsulate the obstacle checking function into a private default method called hasObstacles() and reuse it in the turnLeft(), turnRight method.

3. Conclusions

The tutorial has illustrated how to use private interface methods in Java 9. Even this is a small change in Java 9 features, it allows nonabstract methods of an interface to share code between them, and therefore improve our code reusability.

Below are other related tutorials:

Java 9 JShell Cheat Sheet

Install Oracle Java 9 on CentOS, RHEL 7

Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)

Set Up Eclipse, IntelliJ And NetBeans For Java 9

Java 9 Example With Maven And JUnit 5

Create Immutable Lists In Java 9 By Static Factory Methods

Using The InputStream.transferTo() To Copy Streams In Java 9

Java 9 – New Methods Of The Optional Class

Streams API Updates In Java 9

How To Compare Arrays In Java 9