Video in progress
Why were default methods added to interfaces?
In Java 8, to add new methods to old interfaces without breaking the thousands of classes that implement them. A default method comes with a body, and classes can override it if they want.
📖 Answer
The problem was this: stream() needed to be added to the Collection interface. If it were an ordinary abstract method, every Collection implementation in the world would stop compiling. The solution:
public interface Collection<E> extends Iterable<E> {
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
Use them the same way in your own code:
public interface PriceRule {
long apply(long price);
default PriceRule andThen(PriceRule next) {
return p -> next.apply(apply(p));
}
}
Things to watch:
- a default method can't access instance fields, because interfaces don't have them; it can only call other interface methods;
- you can't make
equals,hashCodeortoStringdefault: the version inObjectalways wins, and the compiler forbids it; - if two interfaces have the same default method, the class is forced to override it.
Don't abuse default methods to turn an interface into a stateless abstract class. They are mainly for extension and convenience methods.
Sign up to mark studied questions and save your progress.