In Scala, traits can have an implementation, so why not have implementations in Java? Well, that was introduced in Java 8, so the next natural step in Java 9 is to have private logic in interfaces. In Part 2 of this series, we introduced the Java 9 REPL. In this part, we are going to examine the new functionality introduced to interfaces.

Java 9 is introducing a lot of new concepts, such as REPL, factory methods for common data structures, and more. Let’s see what Java 9 has to say about private methods in interfaces.

Although we refer to the previous tutorial, we really like to start from zero — and what zero means for us is going to the website where you can download Java 9 and installing it. We'll do that in step one, as we don't like incomplete tutorials.

Our plan:

Download Java 9 from scratch and install

Create a Java 8 style interface with the default implementation

Implement the interface and call it

Enrich the interface with a private method. Run the class and see that it reuses the private interface method.

Step 1: Download Java 9

Although we already covered downloading Java 9, we always want to start from the ground floor. We don’t want to force you to go to another tutorial in order to get any step, so here is how to download it into your macOS.

So now we have an interface called MyInterface. In the next step, we are going to implement it.

Step 3: Implement and Calling the Interface

So let’s implement the interface and then call it. We are not going to define any methods in the class, so the default implementation would come from the, you guessed it, the default implementation in the interface.

As you could see, the REPL nicely replaced our definition of the interface and has doubled and doubleddDoubled our 2 by reusing the private method defined in the interface MyInterface.helpDouble.

Summary

After using REPL in the previous tutorial, we went on to investigate Java 9 by checking out its private interface methods. We started again from ground zero. We downloaded Java 9 from scratch, then ran JShell, the new REPL provided by Java 9. We then defined and ran our first interface with a default implementation, then created a class to implement that interface (but that’s so Java 8). So we went on and defined a private method with an implementation in the interface that helped the public interface implementations! Stay tuned for the next parts!