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
Example 4-11 , our Parent interface defines a welcome method that sends a message when
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 ();
}
When we come to call this code, in Example 4-12 , the default method is called and our as-
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 ());
}
Now we can extend Parent with a Child interface, whose code is listed in Example 4-13 .
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
Search WWH ::




Custom Search