Java Reference
In-Depth Information
Chapter 9. Default methods
This chapter covers
What default methods are
Evolving APIs in a compatible way
Usage patterns for default methods
Resolution rules
Traditionally, a Java interface groups related methods together into a contract. Any class that
implements an interface must provide an implementation for each method defined by the
interface or inherit the implementation from a superclass. But this causes a problem when
library designers need to update an interface to add a new method. Indeed, existing concrete
classes (which may not be under their control) need to be modified to reflect the new interface
contract. This is particularly problematic because the Java 8 API introduces many new methods
on existing interfaces, such as the sort method on the List interface that you used in previous
chapters. Imagine all the angry maintainers of alternative collection frameworks such as Guava
and Apache Commons who now need to modify all the classes implementing the List interface to
provide an implementation for the sort method too!
But don't worry. Java 8 introduces a new mechanism to tackle this problem. It might sound
surprising, but interfaces in Java 8 can now declare methods with implementation code; this
can happen in two ways. First, Java 8 allows static methods inside interfaces. Second, Java 8
introduces a new feature called default methods that allows you to provide a default
implementation for methods in an interface. In other words, interfaces can provide concrete
implementation for methods. As a result, existing classes implementing an interface will
automatically inherit the default implementations if they don't provide one explicitly. This
allows you to evolve interfaces nonintrusively. You've been using several default methods all
along. Two examples you've seen are sort in the List interface and stream in the Collection
interface.
The sort method in the List interface you saw in chapter 1 is new to Java 8 and is defined as
follows:
default void sort(Comparator<? super E> c){
Collections.sort(this, c);
}
 
Search WWH ::




Custom Search