Java Reference
In-Depth Information
For an object to be
Closeable
it must hold an open resource, such as a file handle that needs
to be closed at some point in time. Again, the interface being called cannot be a pure function
because closing a resource is really another example of mutating state.
In contrast to
Closeable
and
Comparable
, all the new interfaces introduced in order to
provide
Stream
interoperability are expected to be implemented by lambda expressions.
They are really there to bundle up blocks of code as data. Consequently, they have the
@FunctionalInterface
annotation applied.
Using the annotation compels
javac
to actually check whether the interface meets the criter-
ia for being a functional interface. If the annotation is applied to an
enum
,
class
, or
annota-
tion
, or if the type is an interface with more than one single abstract method, then
javac
will generate an error message. This is quite helpful for being able to catch errors easily
when refactoring your code.
Binary Interface Compatibility
As you saw in
Chapter 3
, one of the biggest API changes in Java 8 is to the collections lib-
rary. As Java has evolved, it has maintained backward binary compatibility. In practical
terms, this means that if you compiled a library or application with Java 1 through 7, it'll run
out of the box in Java 8.
Of course, there are still bugs from time to time, but compared to many other programming
platforms, binary compatibility has been viewed as a key Java strength. Barring the introduc-
tion of a new keyword, such as
enum
, there has also been an effort to maintain backward
source compatibility. Here the guarantee is that if you've got source code in Java 1-7, it'll
compile in Java 8.
These guarantees are really hard to maintain when you're changing such a core library com-
ponent as the collections library. As a thought exercise, consider a concrete example. The
stream
method was added to the
Collection
interface in Java 8, which means that any class
that implements
Collection
must also have this method on it. For core library classes, this
problem can easily be solved by implementing that method (e.g., adding a
stream
method to
ArrayList
).
Unfortunately, this change still breaks binary compatibility because it means that any class
outside of the JDK that implements
Collection
—say,
MyCustomList
—must also have im-
plemented the
stream
method. In Java 8
MyCustomList
would no longer compile, and even