Java 8 Static and Default Methods in Interface

1. Overview

In this post, we’ll discuss in depth how to use static and default methods in interfaces and go through some use cases where they can be useful.

As we know, In the Java programming language, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, nested types and private methods(from Java 9).

Method bodies exist only for default methods and static methods (private methods from Java 9). Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

Java 8 brought to the table a few brand new features, including lambda expressions, functional interfaces, method references, streams, Optional, and static and default methods in interfaces.

2. Some Real-world Examples

The stream() method defined in the Collection interface is a good example. You can find below default method in Collection interface.

There are lot's of default and static methods are added to JDK 7 libraries and ensure binary compatibility with code written for older versions of those interfaces.

3. Default Method in Interface

3.1 Why Default Methods in Interfaces Are Needed

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

In a typical design based on abstractions, where an interface has one or multiple implementations, if one or more methods are added to the interface, all the implementations will be forced to implement them too. Otherwise, the design will just break down so default interface methods are an efficient way to deal with this issue. They allow us to add new methods to an interface that are automatically available in the implementations. Thus, there’s no need to modify the implementing classes. In this way, backward compatibility is neatly preserved without having to refactor the implementers.

The default method is used to define a method with a default implementation. You can override the default method also to provide the more specific implementation for the method.

4. Static Method in Interface

Generally, static methods are used to define utility methods.

The idea behind static interface methods is to provide a simple mechanism that allows us to increase the degree of cohesion of a design by putting together related methods in one single place without having to create an object.

Furthermore, static methods in interfaces make possible to group related utility methods, without having to create artificial utility classes that are simply placeholders for static methods.