When to Use Java 8 Default Methods in Interfaces
When should you use Java 8 default methods?
Join the DZone community and get the full member experience.
Join For FreeOne of the Oracle’s articles describes in great detail when Default methods should be used:
The section Interfaces describes an example that involves manufacturers of computer-controlled cars who publish industry-standard interfaces that describe which methods can be invoked to operate their cars. What if those computer-controlled car manufacturers add new functionality, such as flight, to their cars? These manufacturers would need to specify new methods to enable other companies (such as electronic guidance instrument manufacturers) to adapt their software to flying cars. Where would these car manufacturers declare these new flight-related methods? If they add them to their original interfaces, then programmers who have implemented those interfaces would have to rewrite their implementations. If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
Here is what we can deduct:
- Default method (Defender methods) should be used for backward compatibility. Whenever you want to add additional functionality in an existing interface, you can use default methods without breaking any existing implementing classes (Default methods enable us to add new functionality to existing Interfaces without breaking older implementation of these Interfaces).
- Default methods in interfaces were introduced to the Java language in order to evolve the collections library for the Streams API.
- The idea is not to design your solution with default methods in mind, but rather, they are an afterthought.
Java has long history of being backward compatible:
- With backward compatability in mind, Java generics are a Type Erasure instead of reifiable Type
- With backward compatability in mind, we still find AWT.
- With backward compatability in mind, we still have Vector (event thought we have
Arraylist
andCopyOnWriteArrayList
) - And then, with backward compatability in mind, default methods are introduced.
Why Default Methods
It was a smart move to evolve the existing API (collection, for example) and to introduce new programming models (like functional) without breaking a zillion lines of code. For example:
java.util.Collection
— this interface now has methods related to Stream while, at the same time, being compatible with existing version.-
java.lang.Iterable
— this interface now supports functional programming.
Published at DZone with permission of Mohammad Nadeem, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments