Java Reference
In-Depth Information
Pay special attention to the way that the default method
getNextArray( )
is implemented.
Because
getNext( )
was part of the original specification for
Series
, any class that imple-
ments
Series
will provide that method. Thus, it can be used inside
getNextArray( )
to ob-
tain the next
n
elements in the series. As a result, any class that implements the enhanced
version of
Series
will be able to use
getNextArray( )
as is, and no class is required to over-
ride it. Therefore, no preexisting code is broken. Of course, it is still possible for a class to
provide its own implementation of
getNextArray( )
, if you choose.
As the preceding example shows, the default method provides two major benefits:
It gives you a way to gracefully evolve interfaces over time without breaking existing
code.
It provides optional functionality without requiring that a class provide a placeholder
implementation when that functionality is not needed.
In the case of
getNextArray( )
, the second point is especially important. If an implement-
ation of
Series
does not require the capability offered by
getNextArray( )
, it need not
provide its own placeholder implementation. This allows cleaner code to be created.
Multiple Inheritance Issues
As explained earlier in this topic, Java does not support the multiple inheritance of classes.
Now that an interface can include default methods, you might be wondering if an interface