Interface Default Methods in Java 8

Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the Interfaces without breaking the existing implementation of these Interface. It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.

Let consider small example to understand how it works:

public interface OldInterface {
    public void existingMethod();

    default public void newDefaultMethod() {
        System.out.println("New default method"
               + " is added in interface");
    }
}

The following Class will compile successfully in Java JDK 8:

public class OldInterfaceImpl implements OldInterface {
    public void existingMethod() {
     // existing implementation is here…
    }
}

If we create an instance of OldInterfaceImpl:

OldInterfaceImpl obj = new OldInterfaceImpl ();
// print “New default method add in interface”
obj.newDefaultMethod();  

Why Default Method?

Reengineering an existing JDK framework is always very complex. Modify one Interface in JDK framework breaks all Classes that extends the Interface which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extending Interfaces in a backward compatible way.

Default methods can be provided to an Interface without affecting implementing Classes as it includes an implementation. If each added method within Interface defined with implementation then no implementing Class is affected. An implementing Class can override the default implementation provided by the Interface.

For Java 8, the JDK collections have been extended and forEach method is added to the entire collection (which work in conjunction with lambdas). With conventional way, the code looks like below:

public interface Iterable<T> {
    public void forEach(Consumer<? super T> consumer);
}

Since this result each implementing Class with compile errors, as a result, a default method added with a required implementation in order that the existing implementation should not be changed. The Iterable Interface with the Default method is below:

public interface Iterable<T> {
    public default void forEach(Consumer
                   <? super T> consumer) {
        for (T t : this) {
            consumer.accept(t);
        }
    }
}

The same mechanism has been used to add Stream in JDK Interface without breaking the implementing Classes.

When to use Default Method over Abstract Classes

Abstract Classes versus Interfaces in Java 8

After being introduced Default Method, the Interfaces and abstract Classes seems similar, however, they still different concept in Java 8. Abstract Class can define constructor. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other Interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.

Default Method and Multiple Inheritance Ambiguity Problems

Since java Class can implement multiple Interfaces and each Interface can define default method with same method signature, therefore, the inherited methods can conflict with each other.

Consider below example:

public interface InterfaceA {  
       default void defaultMethod(){  
           System.out.println("Interface A default method");  
    }  
}

public interface InterfaceB {
   default void defaultMethod(){
       System.out.println("Interface B default method");
   }
}

public class Impl implements InterfaceA, InterfaceB  {
}

The above code will fail to compile with the following error, java: class Impl inherits unrelated defaults for defaultMethod() from types InterfaceA and InterfaceB

In order to fix this class, we need to provide default method implementation:

public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
    }
}

Further, if we want to invoke default implementation provided by any of super Interface rather than our own implementation, we can do so as follows:

public class Impl implements InterfaceA, InterfaceB {
    public void defaultMethod(){
        // existing code here.
        InterfaceA.super.defaultMethod();
    }
}
We can choose any default implementation or both as part of our new method.

Difference between Default Method and Regular Method

Default Method is different from the regular method in the sense that default method comes with default modifier. Additionally, methods in Classes can use and modify method arguments as well as the fields of their Class but default method, on the other hand, can only access its arguments as Interfaces do not have any state.

In summary, Default methods enable to add new functionality to existing Interfaces without breaking older implementation of these Interfaces.
When we extend an interface that contains a default method, we can perform the following action:

  • Not override the default method and will inherit the default method.
  • Override the default method similar to other methods we have overridden subclasses.
  • Redeclare default method as abstract, which will force subclasses to override it.

References

Comments (13)

Loading... Logging you in...
  • Logged in as
Whoa these days lots of buzz is going on default methods , once java 8 is officially release it i am sure that most of the applications will definitely going to use it.

The reason why i think till now there was always a constraint that if we want to introduce some new method (prior to java 8) in an interface ,then it can break the whole application as all the implementation will be forced to provide an implementation for that ,so in that case we try to solve this problem by introducing a new interface to include that new method and i think here we violate the Single Responsibility Model (as its not stated anywhere).

Again I personally feel that Abstract classes have their own cost of using them in terms of multiple inheritance and I also feel that Default methods and abstract classes have there own place in Java and they can't replace each other.
1 reply · active 483 weeks ago
All classes should resemblance its own method except for interface and uniform methods.As per core java usage the classes need to intact with each other.This is a must to know for all developers
Core java refers to the core or basic concepts of the Java programming language. Things like encapsulation, inheritance, multi-threading, exception handling and other basic feature of Java that comes as part of the Java standard edition forms core Java. ONLINEITGURU Offers JAVA frameworks, javascript, JAVA programming, Multithreading in JAVA, event handling in JAVA training in USA, UK, Canada, Australia, India, Singapore. FREE DEMO 100% Live Projects.
Clean interfaces's avatar

Clean interfaces · 561 weeks ago

Very well thank you very much
تنظيف واجهات's avatar

تنظيف واجهات · 558 weeks ago

Very good
fariz lucky's avatar

fariz lucky · 552 weeks ago

Again I personally feel that Abstract classes have their own cost of using them in terms of multiple inheritance and I also feel that Default methods and abstract classes have there own place in Java and they can't replace each other.
karburator pe 28's avatar

karburator pe 28 · 531 weeks ago

Again I personally feel that Abstract classes have their own cost of using them in terms of multiple inheritance and I also feel that Default methods and abstract classes have there own place in Java and they can't replace each other.
felt it was bit easy way to understand and we will try to make use of it with our students. Thank you.
This saved my life today. Wasted hours on understanding how it works. Thanks a ton :)
Amitava Sarkar's avatar

Amitava Sarkar · 399 weeks ago

Hi, your article really nice. That is so logical and clearly explained. Keep it up! I will follow up your blog for the future post.
anurag singh's avatar

anurag singh · 385 weeks ago

This is really very nice and very useful post about java 8 default method.
Thanks for sharing this article.
Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.
Very Informative and insightful article. You have explained java 8 and its default methods very clearly and precise, thanks a lot for sharing. Will be looking forward reading more from you!

Post a new comment

Comments by