A blog on Java 9 changes for
Evolution of interfaces in Java:
Until Java 7, all versions of Java maintained the same set of features for interfaces. Interfaces can
- act as contracts for implementations
- be used for stamping as a parent class to facilitate a Liskov Substitution Principle (Wikipedia: https://en.wikipedia.org/wiki/Liskov_substitution_principle)
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.
abstractmethods – Method signatures as contracts that had to be implemented by the class that implemented the interface.
defaultmethods – 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
staticmethods – 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
privatemethods – 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|
|public static methods|
|private static methods|
Modifier combinations in Java 9
|[public] (naturally abstract)||supported|
|private abstract||compile-time error|
|private default||compile-time error|