Java 8 Default Methods in Interface

Interfaces went through major changes while redesign in Java 8 and as a part of that Java 8 default methods in Interface are the major addition. Java 8 interfaces also supports static methods along with default and abstract methods. Let’s dig into the more details to know the facts about default methods in interfaces.

What is Default Method in Java 8?

Default Method is a new feature which allows programmer to add new methods to the interfaces without affecting the existing implementation of that interface.

Why Default Method is added in Java 8?

In Java 8 Lambda expressions are introduced. It was quite difficult for Java people to add support of lambda expressions in existing collection interfaces. To add a support of Lambda expressions, they need to rewrite all interfaces of collection framework which would have broken the backward compatibility of collection framework with earlier versions of Java. Due to this reason they have introduced concept of Default Methods in interfaces by which programmer can easily add new methods with default keyword in existing interface code without loosing the compatibility.

It is not a natural feature of Java 8, It has appeared as a feature due to Java Collection API updates to enable support of lambda expressions in Java 8.

/**
 * Drawable Interface 
 *  
 */
interface Drawable{
    default void drawShape(Point... points){
        Arrays.asList(points).stream()
            .forEach(p -> System.out.println(p));
    }
    
    void drawLine(Point point1, Point point2);
    void drawTriangle(Point point1, Point point2, Point point3);
}

In above interfaces Drawable has provided default implementation of drawShape method which can be used by any class implementing that interface. Even that method can be used by another default method within that interfaces as well as in the child interfaces of Drawable. The most important thing is you cannot modify parameters in default method.

After Java added this feature the Abstract class and Interface difference is narrow down a bit. Let’s see what differences are left now.

Difference between Abstract Class and Interface in Java 8
Abstract Class
  • It can have the constructor defined
  • It is stateful as it can maintain state in a form of instance variable
  • They are mutable in nature as it’s method can change the state
  • Regular methods in class can change the method arguments
Interface
  • No constructor
  • It is Stateless as there is no instance variable to maintain the state
  • They are immutable as the method cannot change the state
  • Default methods in interface can only access the method arguments, can’t modify it
Famous Diamond Problem

After Java added support of default methods in interfaces our famous C++ diamond problem arise in Java.

Look at the following example,

/**
 * InterfaceOne with defaultImplementation() method
 */
interface InterfaceOne{
    default void defaultImplementation(){
        System.out.println("Default Implementation of InterfaceOne");
    }
}

/**
 * InterfaceTwo with defaultImplementation() method
 */
interface InterfaceTwo{
    default void defaultImplementation(){
        System.out.println("Default Implementation of InterfaceTwo");
    }
}

/**
 * Compilation Error:
 *   Duplicate default methods named defaultImplementation with the 
 *   parameters () and () are inherited from the types InterfaceTwo and InterfaceOne
 */
class DiamondClass implements InterfaceOne, InterfaceTwo{
    
}

In above code snippet, InterfaceOne and InterfaceTwo have the same default method definition of defaultImplementation(). Now when class DiamondClass implement both of these interfaces, it cannot make a choice for choosing between both default methods as both of them have same name and signature. This problem is referred as a Diamond problem.

Solution in Java

As a solution, You can define a brand new public method with the same name and signature with two options,

Java 8 Default Methods
Java 8 Default Methods

1) New method with completely new implementation

/**
 * New public method with completely new implementation  
 */
class DiamondClass implements InterfaceOne, InterfaceTwo{
    public void defaultImplementation(){
        System.out.println("Default Implementation of DiamondClass");
    }
}

2) New method which eventually call the parent method from any of the Interface using <INTERFACE_NAME>.super syntax

/**
 * New public method calling parent interface method  
 */
class DiamondClass implements InterfaceOne, InterfaceTwo{
    public void defaultImplementation(){
        InterfaceOne.super.defaultImplementation();
        // OR
        // InterfaceTwo.super.defaultImplementation();
    }
}

That’s it. Now your concepts are refined with Java 8 Default Methods of interfaces…..!!!!!

nJoy Learning with backtobazics.com …..!!!!!

References

https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

2 thoughts on “Java 8 Default Methods in Interface”

Leave a Reply to Jignesh Cancel reply

Your email address will not be published. Required fields are marked *

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>