Java Tip of the Week #8 – Java 8 Default Methods

posted by Roberto Cortez on

This week Java Tip of the Week we continue to explore some of the new features introduced in Java 8. This time is about Default Methods.

Before Java 8, Interfaces were a closed contract, meaning that after you published an Interface, every implementation would have to implement every method present in the Interface. If you changed your mind later and wanted to add new methods, you couldn’t without breaking the compatibility. Implementations would need to add the missing code to the new methods. The Collections API is a good example. It was designed since the early versions of Java, but it was missing operations that would help every day developer.

With Java 8, we can now implement methods in the Interface directly. This is done via a Default Method with the default keyword. As the name says, we are providing a default implementation for the method. So, if any implementation does not implement the method, it would use the default implementation. This change allowed to expand and extend API’s behaviour without breaking compatibility.

Default Method Interface

Here is a sample:

Yes, this works!

Check out this video with some live coding examples:

Remember to follow my Youtube channel for faster updates!

Leave a comment if you enjoyed it, if not leave one as well!

Leave a reply

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>