Java Reference
In-Depth Information
Add the new method, along with its implementation, to the utility class interface as a
default method. By doing so, each class that implements the interface will automatic-
ally gain use of the new method, and will not be forced to implement it since a default
implementation exists. The following class interface contains a default method, which
can be used by any class that implements the interface.
public interface TeamType {
List<Player> getPlayers();
void setPlayers(List<Player> players);
void setName(String name);
void setCity(String city);
String getFullName();
default void listPlayers() {
getPlayers().stream().forEach((player) -> {
System.out.println(player.getFirstName() + "
" + player.getLastName());
});
}
}
The interface TeamType contains a default method named listPlayers() .
This method does not need to be implemented by any classes that implement
TeamType since there is a default implementation contained within the interface.
How It Works
In previous releases of Java, interfaces could only contain method signatures and con-
stant variables. It was not possible to define a method implementation within an inter-
face. This works well in most cases, as interfaces are a construct that is meant to en-
force type safety and abstract implementation details. However, in some circumstances,
it is beneficial to allow interfaces to contain a default method implementation. For in-
Search WWH ::




Custom Search