Java Reference
In-Depth Information
9.3. Usage patterns for default methods
You've seen how default methods can be useful to evolve a library in a compatible way. Is there
anything else you can do with them? You can create your own interfaces that have default
methods too. You may want to do this for two use cases that we explore in this section: optional
methods and multiple inheritance of behavior .
9.3.1. Optional methods
It's likely you've come across classes that implement an interface but leave empty some method
implementations. Take, for example, the Iterator interface. It defines hasNext and next but also
the remove method. Prior to Java 8, remove was often ignored because the user decided not to
use that capability. As a result, many classes implementing Iterator have an empty
implementation for remove, which results in unnecessary boilerplate code.
With default methods, you can provide a default implementation for such methods, so concrete
classes don't need to explicitly provide an empty implementation. For example, the Iterator
interface in Java 8 provides a default implementation for remove as follows:
interface Iterator<T> {
boolean hasNext();
T next();
default void remove() {
throw new UnsupportedOperationException();
}
}
Consequently, you can reduce boilerplate code. Any class implementing the Iterator interface
doesn't need to declare an empty remove method anymore to ignore it, because it now has a
default implementation.
9.3.2. Multiple inheritance of behavior
Default methods enable something that wasn't possible in an elegant way before: multiple
inheritance of behavior . This is the ability of a class to reuse code from multiple places, as
illustrated in figure 9.3 .
 
Search WWH ::




Custom Search