Java Reference
In-Depth Information
To solve this problem, a new mechanism was needed, essentially to allow interfaces
to evolve by allowing new, optional methods to be added to interfaces without
breaking backward compatibility.
Implementation of default methods
To add new methods to an interface without breaking backward compatability
requires that some implementation must be provided for the older implementations
of the interface so that they can continue to work. This mechanism is a default
method, and it was first added to the platform in JDK 8.
A default method (sometimes called an optional method) can
be added to any interface. This must include an implementa‐
tion, called the default implementation , which is written inline
in the interface definition.
The basic behavior of default methods is:
• An implementing class may (but is not required to) implement the default
• If an implementing class implements the default method, then the implementa‐
tion in the class is used.
• If no other implementation can be found, then the default implementation is
An example default method is the sort() method. It's been added to the interface
java.util.List in JDK 8, and is defined as:
// The <E> syntax is Java's way of writing a generic type—see
// the next section for full details. If you aren't familiar with
// generics, just ignore that syntax for now.
interface List < E > {
// Other members omitted
public default void sort ( Comparator <? super E > c ) {
Collections .< E > sort ( this , c );
Thus, from Java 8 upward, any object that implements List has an instance method
sort() that can be used to sort the list using a suitable Comparator . As the return
type is void , we might expect that this is an in-place sort, and this is indeed the case.
Marker Interfaces
Sometimes it is useful to define an interface that is entirely empty. A class can imple‐
ment this interface simply by naming it in its implements clause without having to
Search WWH ::

Custom Search