Thursday, September 11, 2014

Java 8 : Default Methods

This are methods declared only in interfaces with ‘default’ keyword to provide default implementation.

public interface DefaultInterface {
       default public void method() {
              System.out.println("Default implementation");
       };
}

This type interfaces will not force classes to implement the interface methods and they provide implementation.

These interfaces helps designers to add methods on top level interfaces to add more functionality.

If two interfaces are providing same method (both are default or one with default) then implementation class must override that method.

If you want to use one of your interface method then you can specify that in implementation using “InterfaceClass.super.methodName”.

public interface Name {
       public String getName();

       public default String getString() {
              return "Name : String";
       }
}
public interface Person {
       default String getName() {
              return "Person : Lenin";
       };
}

public class Employee implements Person, Name {
       public String getName() {//must override this method.
              return "Employee : Lenin";
       }
       //getString method is optional as there is no ambiguity.
}

public class Employee implements Person, Name {
       public String getName() {//must override this method.
              return Person.super.getName();//specifying interface method.
       }
//getString method is optional as there is no ambiguity.
}

If some any class implements Employee then getName will called from Employee only.
Here Class wins for this method as it is implemented in Class.

Note:
  1. We can never make default method for Object class methods.
  2. If you add default methods to interface it has no effect on code that worked before there were default methods.



No comments:

Post a Comment