Java 8 Default Methods

In previous post, we learned about Java 8 functional interface example. Now, let’s move on the discussion and talk about another related feature i.e. Java 8 default methods. Java 8 introduces a new concept of default method implementation in interfaces. For creating a default method in java interface, we need to use “default” keyword with the method signature.

Let’s understand with an example:

The interface above defines a default method sayHello(). If any class implements this interface it can directly call the default method of this interface. This feature helps us in extending interfaces with additional methods, all we must provide a default implementation.

Output: sayHello() from InterfaceA

Why default methods were needed in java 8?

Interface default methods help us in extending interfaces without having the fear of breaking implementation classes.

Interface default methods help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.

In Java 8, one of the major reasons for introducing interface default methods is to enhance the Collections API to support lambda expressions.

Let’s see an example. Below is a method which has been added to java.lang.Iterable in Java 8.

Before java 8, if you had to iterate on a java collection, you have to get an iterator instance and call it’s next method until hasNext() returns false.

How conflicts are resolved while calling default methods?

So far so good. The default methods make me confused in case of multiple inheritance( a class implements one more interfaces or a interface extends one more other interfaces. Rules for this conflict resolution are as follows:

If a class implements directly or interface extends directly two interfaces have a default method with the same signature, then serious conflict condition happen, and compiler error happen. Here, you must override one of default method by calling super method.

A default method cannot override a method from java.lang.Object. Because Object is the base class for all the java classes. We can’t have default methods that are overriding Object class methods.

In java 8, interface default methods are also referred to as Defender Methods or Virtual extension methods.

That’s all for the topic Java 8 Default Methods

References
Default Methods

Download complete source code, click link below


Java8-Default-Method.zip (0 downloads)

Please share it if you found this useful
Hide Buttons