Tuesday, May 24, 2016

default() method in Java 8

Earlier interfaces have only methods without body/implementation. That means Classes implementing that interface must have implement that method.

From java8, with introduction of default keyword, one can give default implementation in interface itself which means if implementation is not there in concrete class, JVM will by default take default implementation.

public class DefaultMethod implements InterfaceA {

     public static void main(String[] args) {
           DefaultMethod df = new DefaultMethod();
           df.sayHi();
     }

     @Override
     public void saySomething() {
     }

}

interface InterfaceA {
     public void saySomething();

     /* Earlier we used to provide implementation in concrete class only.
      * By Adding the keyword default before the method’s access modifier, we do
      * not have to provide implementation for the method sayHi() in class
      * DefaultMethod.
      */

     default public void sayHi() {
           System.out.println("Hi frm InterfaceA. Not implemented in Class");
     }
}

Output:
Hi from InterfaceA. Not implemented in Class


What if there are two interfaces with same default method? How will concrete class call one interface default method?

public class DefaultMethod implements InterfaceA, InterfaceB {

     public static void main(String[] args) {
           DefaultMethod df = new DefaultMethod();
           df.sayHi();
     }

     @Override
     public void saySomething() {
     }
    
     /* Duplicate sayHi() in both Interface,
     To overcome from diamond problem,must override sayHi()*/
    
     @Override
     public void sayHi() {
           System.out.println("Implemented in main class DefaultMethod");
           InterfaceA.super.sayHi();
           InterfaceB.super.sayHi(); 
     }
}

interface InterfaceA {
     public void saySomething();

     /* Earlier we used to provide implementation in concrete class only.
      * By Adding the keyword default before the method’s access    modifier, we do not have to provide implementation for the method sayHi() in class DefaultMethod.
      */

     default public void sayHi() {
           System.out.println("Hi frm InterfaceA. Not implemented in Class");
     }
}

interface InterfaceB {
     default public void sayHi() {
           System.out.println("Hi frm InterfaceB. Not implemented in Class");
     }
}

Output:
Implemented in main class DefaultMethod
Hi frm InterfaceA. Not implemented in Class

Hi frm InterfaceB. Not implemented in Class

No comments:

Post a Comment