Java Reference
In-Depth Information
if you had a compiled version when you tried to load
MyCustomList
into a JVM, it would
result in an exception being thrown by your
ClassLoader
.
This nightmare scenario of all third-party collections libraries being broken has been averted,
but it did require the introduction of a new language concept:
default methods
.
Default Methods
So you've got your new
stream
method on
Collection
; how do you allow
MyCustomList
to compile without ever having to know about its existence? The Java 8 approach to solving
the problem is to allow
Collection
to say, “If any of my children don't have a
stream
method, they can use this one.” These methods on an interface are called
default
methods.
They can be used on any interface, functional or not.
Another default method that has been added is the
forEach
method on
Iterable
, which
provides similar functionality to the
for
loop but lets you use a lambda expression as the
body of the loop.
Example 4-10
shows how this could be implemented in the JDK.
Example 4-10. An example default method, showing how forEach might be implemented
default
default
void
void
forEach
(
Consumer
<?
super
super
T
>
action
) {
for
for
(
T t
:
this
this
) {
action
.
accept
(
t
);
}
}
Now that you're familiar with the idea that you can use lambda expressions by just calling
methods on interfaces, this example should look pretty simple. It uses a regular
for
loop to
iterate over the underlying
Iterable
, calling the
accept
method with each value.
If it's so simple, why mention it? The important thing is that new
default
keyword right at
the beginning of the code snippet. That tells
javac
that you really want to add a method to
an interface. Other than the addition of a new keyword,
default
methods also have slightly
different inheritance rules to regular methods.
The other big difference is that, unlike classes, interfaces don't have instance fields, so
de-
fault
methods can modify their child classes only by calling methods on them. This helps
you avoid making assumptions about the implementation of their children.