A default method is a feature introduced in Java 8 which allows an interface to declare a method body. Classes which implement the interface are not required to override a default method. Use this tag for questions relating to default methods.
A default method is a feature introduced in java-8 which allows an interface to declare a method body. Classes which implement the interface are not required to override a default method. An interface method is made default by adding the default
keyword, also introduced in Java 8.
In the following example, then
method is a default method of the Command
interface.
@FunctionalInterface
interface Command {
void execute();
default Command then(Command next) {
return () -> {
this.execute();
next.execute();
};
}
}
Adding a default method to an interface or changing a method from abstract to default does not break compatibility with a pre-existing binary if the binary does not attempt to invoke the method.
See also:
- Interface Method Body in the Java Language Specification
- Interface Method Declarations in the Java Language Specification for binary compatibility
- Official default methods tutorial
- Java 8 default methods as traits : safe?