Java Reference
In-Depth Information
Now, when
getAdminID( )
is called, a value other than its default is returned.
A More Practical Example of a Default Method
Although the preceding shows the mechanics of using default methods, it doesn't illustrate
their usefulness in a more practical setting. To do this, let's return to the
Series
interface
shown earlier in this chapter. For the sake of discussion, assume that
Series
is widely used
and many programs rely on it. Further assume that through an analysis of usage patterns, it
was discovered that many implementations of
Series
were adding a method that returned
an array that contained the next
n
elements in the series. Given this situation, you decide to
enhance
Series
so that it includes such a method, calling the new method
getNextArray( )
and declaring it as shown here:
Here,
n
specifies the number of elements to retrieve. Prior to default methods, adding this
method to
Series
would have broken preexisting code because existing implementations
would not have defined the method. However, by providing a default for this new method,
it can be added to
Series
without causing harm. Let's work through the process.
In some cases, when a default method is added to an existing interface, its implementa-
tion simply reports an error if an attempt is made to use the default. This approach is neces-
sary in the case of default methods for which no implementation can be provided that will
work in all cases. These types of default methods define what is, essentially, optional code.
However, in some cases, you can define a default method that will work in all cases. This is
the situation for
getNextArray( )
. Because
Series
already requires that a class implement
getNext( )
, the default version of
getNextArray( )
can use it. Thus, here is one way to im-
plement the new version of
Series
that includes the default
getNextArray( )
method: