Square CSS

Monday, May 25, 2020

Java 8 : Default Method In Interface

Introduction


Java 8 comes with use of default method in an interface. Multiple Interfaces can have the same default method.

Refer The Video For More Detail




Uses of Default Method


We can create a method with default keyword and the method will be referred from the interface.


  public interface DefaultInterface{
public default void getDefault() {
        //Custom Code
      }
  }


In case if two interface have same default method then at the time of compilation only the editor will ask for the implementation of default method. 



  public interface DefaultInterface1 {
public default void getDefault() {
               System.out.println("Default Interface1");
       }
  }


public interface DefaultInterface2 {
public default void getDefault() {
                System.out.println("Default Interface2");

       }
  }


When a class implements the above two interface then the user needs to override the default method of either of the interface. This will remove the diamond problem which occurs in multiple inheritance.



  public class ImplementInterfaceWithDefaultMethod
implements DefaultInterface1,DefaultInterface2{

    @Override
   public void getDefault() {
DefaultInterface1.super.getDefault();
        
   }


Conclusion


The default method can be created inside the interface since Java 8. It can be used by calling the Interface with its default method using super keyword.


No comments:

Post a Comment

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts