Social Media

Java8 – Methods in Interfaces

My previous post on streams demonstrates how useful this feature is to Java8. However it created a problem for the API designers. The problem was how to we extend the existing Collection’s API without breaking existing Collections implementations(guava, apache).

The solution was to allow methods in interfaces, meaning that any implementations already carry an implementation of the extension.

A good example is –

Rules on default methods

  • Always public
  • default – keyword

Multiple Inheritance

Java always had multiple inheritance in interfaces, but it wasn’t an issue as it didn’t matter which version of the inherited method was implemented.

It’s more complex when default methods are involved, and java 8 has an order of precedence –

  • classes > interfaces
  • children > parent
  • else select or override implementation

Examples

  • Classes > Interfaces –

  • Child Interfaces > Parent Interfaces –

  • Re-implement method in the DefaultMethodsClass and call the specific implementation using super –

eg –

static methods

The reasoning here is to keep static methods specific to your interface in one location –

  • public
  • static
  • Never inherited

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About

follow me on:

Leave a Comment:

1 comment
My Top Java 9 Features - javabullets says 27/09/2017

[…] Methods In Interfaces – Java8 introduced default and static methods in interfaces allowing us to add behaviour to interfaces. Private methods build on this by allowing default […]

Reply
Add Your Reply