The two main purposes I see in default
methods (some use cases serve both purposes):
- Syntax sugar. A utility class could serve that purpose, but instance methods are nicer.
- Extension of an existing interface. The implementation is generic but sometimes inefficient.
If it was just about the second purpose, you wouldn't see that in a brand new interface like Predicate
. All @FunctionalInterface
annotated interfaces are required to have exactly one abstract method so that a lambda can implement it. Added default
methods like and
, or
, negate
are just utility, and you aren't supposed to override them. However, sometimes static methods would do bettersometimes static methods would do better.
As for extension of existing interfaces - even there, some new methods are just syntax sugar. Methods of Collection
like stream
, forEach
, removeIf
- basically, it's just utility you don't need to override.
And then there are methods like spliterator
. The default implementation is suboptimal, but hey, at least the code compiles. Only resort to this if your interface is already published and widely used.
As for the static
methods, I guess the others cover it quite well: It allows the interface to be its own utility class. Maybe we could get rid of Collections
in Java's future? Set.empty()
would rock.