Java 9 Features – Private Interface Methods

java, java 9, technology

Duke-Java9

A blog on Java 9 changes for interfaces.

Evolution of interfaces in Java:

Until Java 7, all versions of Java maintained the same set of features for interfaces. Interfaces can

Interfaces contained method signatures and were useful for storing public constants. Since then, constants have remained a staple of the interface. Recent changes have been more focused on methods.

Java 7

  • abstract methods – Method signatures as contracts that had to be implemented by the class that implemented the interface.

Java 8

  • default methods – Methods with an implementation in the interface, providing an option to the implementing class to override.

    This change allowed for extension and growth of existing APIs without major refactoring and without harming backward-compatibility. Best example of this is the Java 8 collection framework that introduced new features on the root interfaces without having to make significant changes to any of the implementations.

    See http://docs.oracle.com/javase/8/docs/api/java/util/List.html for sort(...) or spliterator() or replaceAll(...).

  • static methods – Methods with the static modifier with an implementation, which thus belong to the interface.

    These methods cannot be overwritten in implementing classes. Adding static methods allows the interface to control some behavior without allowing for an implementation to alter such behavior.

    See http://docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html for comparingByKey() or comparingByValue().

Java 9

  • private methods – Methods with implementation in the interface that remain private to the interface alone.

    These methods are useful from an encapsulation perspective to hold some logic that the implementations should not override.

    While there is no concrete example in the JDK API that I could immediately find, there are several existing interfaces which have workarounds for encapsulating private methods via private inner classes. Such workarounds can be circumvented with private methods.

Java support in interfaces

  Java 7 Java 8 Java 9
constants
abstract methods
default methods
public static methods
private methods
private static methods

Modifier combinations in Java 9

Combination Comment
[public] (naturally abstract) supported
[public] default supported
[public] static supported
private supported
private static supported
private abstract compile-time error
private default compile-time error

Leave a comment