Java Reference
In-Depth Information
Suppose we had a custom list implementation called MyCustomList and had implemented a
custom addAll method, and the new List interface provided a default addAll that deleg-
ated to the add method. If the default method wasn't guaranteed to be overridden by this
addAll method, we could break the existing implementation.
Multiple Inheritance
Because interfaces are subject to multiple inheritance, it's possible to get into situations
where two interfaces both provide default methods with the same signature. Here's an ex-
ample in which both a Carriage and a Jukebox provide a method to rock —in each case, for
different purposes. We also have a MusicalCarriage , which is both a Jukebox
( Example 4-19 ) and a Carriage ( Example 4-20 ) and tries to inherit the rock method.
Example 4-19. Jukebox
public
public interface
interface Jukebox
Jukebox {
public
public default
default String rock () {
return
return "... all over the world!" ;
}
}
Example 4-20. Carriage
public
public interface
interface Carriage
Carriage {
public
public default
default String rock () {
return
return "... from side to side" ;
}
}
public
public class
class MusicalCarriage
MusicalCarriage implements
implements Carriage , Jukebox {
}
Because it's not clear to javac which method it should inherit, this will just result in the
compile error class MusicalCarriage inherits unrelated defaults for rock()
from types Carriage and Jukebox . Of course, it's possible to resolve this by implement-
ing the rock method, shown in Example 4-21 .
Search WWH ::




Custom Search