Default method in interface in Java - Java @ Desk

Monday, November 20, 2017

Default method in interface in Java

Default method in interface in Java

Default methods have been introduced in Java 8 in order to extend the feature providing an default implementation across all implementation classes.
The main intention of introducing default method is to have a method with implementation in an existing interface without affecting implementation classes. Introduing a new method declaration in existing interface force the change in all implementation classes. The default method comes with an implementation thus making it all optional for the classes to provide the implementation.
Still, the class can override the default implementation of the default method of interface.
So, interface in Java can define a method. An implementation class may or may not override the default implementation.

package com.learning;

public interface DefaultInterface {

 default public void defaultInterfaceDefinedMethod() {
  System.out.println("Default Interface method is called");
 }
}


package com.learning;

public class DefaultInterfaceImpl implements DefaultInterface {

}


package com.learning;

public class DefaultInterfaceMain {

 public static void main(String args[]) {

  DefaultInterface defaultInterface = new DefaultInterfaceImpl();
  defaultInterface.defaultInterfaceDefinedMethod();
 }

}



For Java 8, the JDK collections have been extended and forEach method is added to the entire collection (which work in conjunction with lambdas). The same mechanism has been used to add Stream in JDK interface without breaking the implementing classes.

What about Multiple Inheritance?
public interface DefaultInterface {

 default public void defaultInterfaceDefinedMethod() {
  System.out.println("Default Interface method is called");
 }
}

public interface DefaultInterfaceTwo {

 default public void defaultInterfaceDefinedMethod() {
  System.out.println("Default Interface Two method is called");
 }
}

public class DefaultInterfaceImpl implements DefaultInterface, DefaultInterfaceTwo {

}


This generates compilation error since the implementation class finds the same default method in both the interfaces. In order to fix this class, we need to provide default method implementation in the class itself i.e. it now becomes mandatory for the class to override the default implementation as shown below
public class DefaultInterfaceImpl implements DefaultInterface, DefaultInterfaceTwo {

 @Override
 public void defaultInterfaceDefinedMethod() {
 }

}


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,
package com.learning;

public class DefaultInterfaceImpl implements DefaultInterface, DefaultInterfaceTwo {

 @Override
 public void defaultInterfaceDefinedMethod() {
  DefaultInterface.super.defaultInterfaceDefinedMethod();
 }

}








No comments:

Post a Comment