Before Java 8, interfaces were subject to some restrictions. All
methods declared in interfaces had to be:
- Abstract, that is, with no implementation
- Non-static, that is, called with an object as the implicit
parameter
In Java 8, these restrictions have been removed.
Java 8 allows interface methods with concrete implementations,
called
default methods.
This allows methods to be added to existing interfaces without
requiring all implementing classes to add them.
For the examples in this section, recall the original
State
interface from the problem solving framework:
When we change the framework to allow automatic solving, a
new
getHeuristic method will be added to the
State interface:
This will require that all implementing classes,
e.g.
FarmerState and
PuzzleState, be changed to include
the
getHeuristic method, even those, such as
FarmerState,
that will not require heuristics.
In Java 8, we can add a default method to the
State interface
with a concrete implementation that suffices for
FarmerState:
Note the use of the "
default" keyword, and the inclusion of the
method body.
Before Java 8, interface methods could not be static. This meant that
if a library designer wanted to define a static method associated with an interface,
he/she had to define a separate class that provides them (e.g.,
the
Collections class associated with the
List interface).
After Java 8, interfaces can define static methods, so all the methods
associated with a given abstraction can be in one place.
For example, without static interface methods, if
PuzzleState
implements
State and
current is an
instance of
PuzzleState, its heuristic is calculated with:
If you wanted to call a static method like:
the method had to be defined in the
PuzzleState class and it
could not be generically used in a framework.
If a static method is added to
State as shown here:
the heuristic can be calculated in generic terms using:
and it can be part of framework code.