Java Reference
In-Depth Information
programmers will need to write default methods themselves and because they facilitate program
evolution rather than helping write any particular program, we keep the explanation here short
and example-based:
In section 1.3 , we gave the following example Java 8 code:
List<Apple> heavyApples1 =
inventory .stream() .filter((Apple a) -> a.getWeight() > 150)
.collect(toList());
List<Apple> heavyApples2 =
inventory .parallelStream() .filter((Apple a) -> a.getWeight() > 150)
.collect(toList());
But there's a problem here: a List<T> prior to Java 8 doesn't have stream or parallel-Stream
methods—and neither does the Collection<T> interface that it implements—because these
methods hadn't been conceived of! And without these methods this code won't compile. The
simplest solution, which you might employ for your own interfaces, would have been for the
Java 8 designers simply to add the stream method to the Collection interface and add the
implementation in the ArrayList class.
But doing this would have been a nightmare for users. There are many alternative collection
frameworks that implement interfaces from the Collections API. Adding a new method to an
interface means all concrete classes must provide an implementation for it. Language designers
have no control on all existing implementations of Collections, so you have a bit of a dilemma:
how can you evolve published interfaces without disrupting existing implementations?
The Java 8 solution is to break the last link—an interface can now contain method signatures for
which an implementing class doesn't provide an implementation! So who implements them?
The missing method bodies are given as part of the interface (hence default implementations)
rather than in the implementing class.
This provides a way for an interface designer to enlarge an interface beyond those methods that
were originally planned—without breaking existing code. Java 8 uses the new default keyword in
the interface specification to achieve this.
For example, in Java 8 you can now call the sort method directly on a List. This is made possible
with the following default method in the Java 8 List interface, which calls the static method
Collections.sort:
default void sort(Comparator<? super E> c) {
Collections.sort(this, c);
 
Search WWH ::




Custom Search