Week 115 — What are default methods in interfaces?
Question of the Week #115
What are default methods in interfaces?
3 Replies
Normally, methods defined in interfaces don't have a body and have to be implemented by classes implementing the interface:
When a method in an interface is marked with the
default
modifier, the implementation is provided in the interface but it can still be overridden by implementing classes:
Default methods can be used for adding methods to interfaces without breaking compatibility or if many implementations likely don't need any behavior for the method that is different from the code in the interface.📖 Sample answer from dan1st
Default methods allow interfaces to supply a "default" implementations for their methods. Implementors are not required to provide their own implementations of default methods, although they may, if needed. If no overriding implementation is supplied, the default provided by the interface will be used.
As an example, given the following interface:
The
myDateFormat
method has a default implementation, which allows implementors to omit that method:
.... or to provide a different implementation:
Default implementations were added to Java 8 as a way to enhance existing interfaces with new methods, while still maintaining backwards compatibility. For example, the java.util.Collection
interface introduced the stream()
, parallelStream
, and spliterator
methods to support Streams. Without default methods, all existing Collection
implementations would've been required to implement those 3 new methods. However, the JDK was able to provide implementations that work in the vast majority of cases.
Another benefit is that they allow interfaces with multiple methods to be treated as a @FunctionalInterface
, provided that exactly one method is fully abstract.Default implementations should only be provided for a method if the most commonly needed implementation can be anticipated or inferred.
⭐ Submission from dangerously_casual