Java Reference
In-Depth Information
Example 4-21. Implementing the rock method
public
public class
class
MusicalCarriage
MusicalCarriage
implements
implements
Carriage
,
Jukebox
{
@Override
public
public
String
rock
() {
return
return
Carriage
.
super
.
rock
();
}
}
This example uses the enhanced
super
syntax in order to pick
Carriage
as its preferred
rock
implementation. Previously,
super
acted as a reference to the parent class, but by using
the
InterfaceName.super
variant it's possible to specify a method from an inherited inter-
face.
The Three Rules
If you're ever unsure of what will happen with
default
methods or with multiple inherit-
ance of behavior, there are three simple rules for handling conflicts:
1. Any class wins over any interface. So if there's a method with a body, or an abstract
declaration, in the superclass chain, we can ignore the interfaces completely.
2. Subtype wins over supertype. If we have a situation in which two interfaces are com-
peting to provide a
default
method and one interface extends the other, the subclass
wins.
3.
No rule 3
. If the previous two rules don't give us the answer, the subclass must either
implement the method or declare it
abstract
.
Rule 1 is what brings us compatibility with old code.
Tradeoffs
These changes raise a bunch of issues regarding what an interface really is in Java 8, as you
can define methods with code bodies on them. This means that interfaces now provide a
form of multiple inheritance that has previously been frowned upon and whose removal has
been considered a usability advantage of Java over C++.