Java 8 – Default Methods in Interfaces

java8

In this article, we will explore the Java 8 default method’s feature in interfaces. The Java 8 says “Default methods enable new functionality to be added to the interfaces in libraries and ensure binary compatibility with code written for older versions of those interfaces”.

As Java evolved over the years, the interfaces introduced in the Java library require adding new functionality. If you add new methods in the interface without having default methods feature, all the classes which already implemented the interfaces should undergo for a change. This results in changing thousands of lines of code. To avoid this, the Java 8 introduced default method feature. That is, if you want to add any functionality to the existing interface, you can add it by using the default method feature without affecting the implementations.

Let us see some examples to understand it better. For example, I am declaring “BookInterface” with open and read functionalities. The implementation classes of this interface should provide an open and read method implementations.

package org.smarttechie;
/**
* The interface is intended to open and read. The implementors should implement the methods to open and read.
* @author Siva Prasad Rao Janapati
*
*/
public interface BookInterface {

/**
* The method opens the book
*/
public void openTheBook();

/**
* The method reads the book
*/
public void readTheBook();
}

Now, we will provide the implementation to the above interface.

package org.smarttechie;
/**
* The JavaBookImpl is the implementation of BookInterface
* @author Siva Prasad Rao Janapati
*
*/
public class JavaBookImpl implements BookInterface {

/**
* This opens the book
*/
@Override
public void openTheBook() {
System.out.println("The Java book is opened");
}

/**
* This reads the book
*/
@Override
public void readTheBook() {
System.out.println("Reading the Java book");
 }
}

Now, we thought to provide close functionality to the book interface. If you add close functionality to the book interface, the existing implementation class should undergo a change. With the default method feature, we can add close functionality to the book interface. The default method will be available to all the implementations.

package org.smarttechie;
/**
* The interface is intended to open and read. The implementors should implement the methods to open and read.
* @author Siva Prasad Rao Janapati
*
*/
public interface BookInterface {

/**
* The method opens the book
*/
public void openTheBook();

/**
* The method reads the book
*/
public void readTheBook();

/**
* The default method implementation
*/
public default void closeTheBook() {
System.out.println("Closting the book");
 }
}
package org.smarttechie;
/**
 * The JavaBookImpl is the implementation of BookInterface
 * @author Siva Prasad Rao Janapati
 *
 */
public class JavaBookImpl implements BookInterface {

 /**
 * This opens the book
 */
 @Override
 public void openTheBook() {
 System.out.println("The Java book is opened");
 }

 /**
 * This reads the book
 */
 @Override
 public void readTheBook() {
 System.out.println("Reading the Java book");
 }

 public static void main (String[] args) {

 BookInterface bookInter = new JavaBookImpl();

 //Call the default method declared in BookInterface
 bookInter.closeTheBook();

 JavaBookImpl book = new JavaBookImpl();
 book.closeTheBook();
 }
}

The byte code of the above method calls is given below. From the byte code, we can say the default methods are “virtual methods”.

Bytecode

If you want, you can override the default method in the implementation class.

package org.smarttechie;
/**
 * The JavaBookImpl is the implementation of BookInterface
 * @author Siva Prasad Rao Janapati
 *
 */
public class JavaBookImpl implements BookInterface {

 /**
 * This opens the book
 */
 @Override
 public void openTheBook() {
 System.out.println("The Java book is opened");
 }

 /**
 * This reads the book
 */
 @Override
 public void readTheBook() {
 System.out.println("Reading the Java book");
 }

 /*
 * This closes the book
 */
 public void closeTheBook() {
 System.out.println("Closing the JAVA book");
 }

 public static void main (String[] args) {
 BookInterface book = new JavaBookImpl();
 book.closeTheBook();
 }
}

By this time you might have got a question, what if we implement two interfaces which have the same default method signature? In that case, the implementation class will get the below compilation error.

“Duplicate default methods named closeTheBook with the parameters () and () are inherited from the types TechBookInterface and BookInterface”

package org.smarttechie;
public interface TechBookInterface {

/**
* The default method implementation
*/
public default void closeTheBook() {
System.out.println("Closing the book");
 }
}
package org.smarttechie;
/**
* The JavaBookImpl is the implementation of BookInterface
* @author Siva Prasad Rao Janapati
*
*/
public class JavaBookImpl implements BookInterface, TechBookInterface {

/**
* This opens the book
*/
@Override
public void openTheBook() {
System.out.println("The Java book is opened");
}

/**
* This reads the book
*/
@Override
public void readTheBook() {
System.out.println("Reading the Java book");
}

public static void main (String[] args) {
BookInterface book = new JavaBookImpl();
book.closeTheBook();
 }
}

To avoid the compilation error, we need to explicitly define the method with the same signature in the implementation class.

package org.smarttechie;
/**
* The JavaBookImpl is the implementation of BookInterface
* @author Siva Prasad Rao Janapati
*
*/
public class JavaBookImpl implements BookInterface, TechBookInterface {

/**
* This opens the book
*/
@Override
public void openTheBook() {
System.out.println("The Java book is opened");
}

/**
* This reads the book
*/
@Override
public void readTheBook() {
System.out.println("Reading the Java book");
}

public void closeTheBook() {
System.out.println("Closing the JAVA book");
}

public static void main (String[] args) {
BookInterface book = new JavaBookImpl();
book.closeTheBook();
 }
}

For further reading, follow the below references.
https://jcp.org/en/jsr/detail?id=335
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Advertisement

Siva Janapati is an Architect with experience in building Cloud Native Microservices architectures, Reactive Systems, Large scale distributed systems, and Serverless Systems. Siva has hands-on in architecture, design, and implementation of scalable systems using Cloud, Java, Go lang, Apache Kafka, Apache Solr, Spring, Spring Boot, Lightbend reactive tech stack, APIGEE edge & on-premise and other open-source, proprietary technologies. Expertise working with and building RESTful, GraphQL APIs. He has successfully delivered multiple applications in retail, telco, and financial services domains. He manages the GitHub(https://github.com/2013techsmarts) where he put the source code of his work related to his blog posts.

Tagged with: ,
Posted in Java
5 comments on “Java 8 – Default Methods in Interfaces
  1. Nona says:

    Great article,

  2. Anonymous says:

    What benefit does this actually present over using an abstract class?

    • If you already have an interface and there are some classes which are implemented, now you want to add new functionality to the interface, then you have to change all the implementations. With default method feature, we can add functionality to Interface with out changing the implementation classes. If you look at the JDK libraries, there are interfaces from the beginning of java. Those interfaces are getting added with new functionality over the period of time.

      • Doug McNally says:

        His point was that you were already able to accomplish this by using an abstract class. The correct response to his question is that Java doesn’t support multiple inheritance – so using abstract classes like interfaces is prohibitive since you can’t “extend” multiple classes, but you can implement as many interfaces as you like.

      • Thanks Doug,

        I think his question is not, what is the use of interfaces over abstract classes?
        His point is, why do we need default method feature for interfaces as we can achieve the same with abstract classes? For this question I gave my answer.

        Your answer is correct for the first question.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Dzone.com
DZone

DZone MVB

Java Code Geeks
Java Code Geeks
OpenSourceForYou
%d bloggers like this: