Java Reference
In-Depth Information
When a class implements more than one interface, it simply means that it must pro‐
vide implementations for all abstract (aka mandatory) methods in all its interfaces.
Default Methods
With the advent of Java 8, it is possible to include methods in interfaces that include
an implementation. In this section, we'll discuss these methods, which represent
optional methods in the API the interfaces represents—they're usually called default
methods . Let's start by looking at the reasons why we need the default mechanism in
the first place.
Backward compatibility
The Java platform has always been very concerned with backwards compatibility.
This means that code that was written (or even compiled) for an earlier version of
the platform must continue to keep working with later releases of the platform. This
principle allows development groups to have a high degree of confidence that an
upgrade of their JDK or JRE will not break currently working applications.
Backward compatibility is a great strength of the Java platform, but in order to ach‐
ieve it, some constraints are placed on the platform. One of them is that interfaces
may not have new mandatory methods added to them in a new release of the
interface.
For example, let's suppose that we want to update the Positionable interface with
the ability to add a bottom-left bounding point as well:
public interface Positionable extends Centered {
void setUpperRightCorner ( double x , double y );
double getUpperRightX ();
double getUpperRightY ();
void setLowerLeftCorner ( double x , double y );
double getLowerLeftX ();
double getLowerLeftY ();
}
With this new definition, if we try to use this new interface with code developed for
the old then it just won't work, as the existing code is missing the mandatory meth‐
ods setLowerLeftCorner() , getLowerLeftX() , and getLowerLeftY() .
You can see this effect quite easily in your own code. Compile
a class file that depends on an interface. Then add a new
mandatory method to the interface, and try to run the pro‐
gram with the new version of the interface, together with your
old class file. You should see the program crash with a
NoClassDefError .
This limitation was a concern for the designers of Java 8—as one of their goals was
to be able to upgrade the core Java Collections libraries, and introduce methods that
made use of lambda expressions.
Search WWH ::




Custom Search