Java Reference
In-Depth Information
Default Methods and Subclassing
There are some subtleties about the way that
default
methods override and can be overrid-
den by other methods. Let's look the simplest case to begin with: no overriding. In
called. The
ParentImpl
class doesn't provide an implementation of
welcome
, so it inherits
the
default
method.
Example 4-11. The Parent interface; the welcome method is a default
public
public interface
interface
Parent
Parent
{
public
public
void
void
message
(
String body
);
public
public default
void
welcome
() {
message
(
"Parent: Hi!"
);
default
void
}
public
public
String
getLastMessage
();
}
sertion passes.
Example 4-12. Using the default method from client code
@Test
public
public
void
void
parentDefaultUsed
() {
Parent parent
=
new
new
ParentImpl
();
parent
.
welcome
();
assertEquals
(
"Parent: Hi!"
,
parent
.
getLastMessage
());
}
Child
implements its own
default welcome
method. As you would intuitively expect, the
default
method on
Child
overrides the
default
method on
Parent
. In this example, again,
the
ChildImpl
class doesn't provide an implementation of
welcome
, so it inherits the
de-
fault
method.
Example 4-13. Child interface that extends Parent
public
public interface
interface
Child
Child
extends
extends
Parent
{
@Override