Java 8 (LTS) · Topic 11 of 12
Default and static interface methods
Definition​
Since Java 8 an interface can contain methods with a body. A default method gives implementing classes a ready-made behaviour they may override, and a static method belongs to the interface itself. This let Java add new methods to old interfaces without breaking existing classes.
Example code​
An interface with a default method and a static helper
interface Greeter {
String name();
default String greet() { // implementing classes get this for free
return "Hello, " + name() + "!";
}
static Greeter of(String name) { // a helper that lives on the interface
return () -> name;
}
}
class Polite implements Greeter {
public String name() { return "Asha"; }
@Override
public String greet() { return "Good morning, " + name(); } // can still override it
}
class Demo {
public static void main(String[] args) {
System.out.println(Greeter.of("Ravi").greet());
System.out.println(new Polite().greet());
}
}
// Output:
// Hello, Ravi!
// Good morning, Asha
Finished this page? Track your progress (saved only in your browser).