Careeroza
Default and Static Methods
Methods with a Body (Java 8+)
| Kind | Keyword | Inherited by implementers? | Called as |
|---|---|---|---|
| Abstract | (none) | must be implemented | obj.m() |
| Default | default | yes, can be overridden | obj.m() |
| Static | static | no | InterfaceName.m() |
| Private (Java 9+) | private | no, helper for default methods | inside the interface only |
Default methods let library authors add new methods to an interface without breaking every class that already implements it. That is how List.sort() and Collection.stream() were added in Java 8.
Example
Example
public class Main {
public static void main(String[] args) {
Discount festive = new FestiveDiscount();
Discount none = new NoDiscount();
System.out.println(festive.apply(1000));
System.out.println(none.apply(1000));
System.out.println(Discount.isValidPrice(-5));
}
}
interface Discount {
double percent();
default String apply(double price) { // shared behaviour
double finalPrice = price - price * percent() / 100;
return label() + " -> " + finalPrice;
}
private String label() { // helper, hidden from implementers
return percent() + "% off";
}
static boolean isValidPrice(double price) { // utility on the interface itself
return price > 0;
}
}
class FestiveDiscount implements Discount {
public double percent() { return 20; }
}
class NoDiscount implements Discount {
public double percent() { return 0; }
@Override
public String apply(double price) { // overriding a default method
return "No discount -> " + price;
}
}Output
20.0% off -> 800.0 No discount -> 1000.0 false