Sunday 22 March 2020

Explicitly invoke the default implementation of a method

Java8 introduces default methods to interfaces. Default methods enables to add new functionality to the existing interfaces, and ensure binary compatibility with code written for older versions of those interfaces.

By using default keyword you can specify a default implementation for a method in interface. All method declarations in an interface, including default methods, are implicitly public.

Sometimes, you may want to override the functionality of default method and at the same time want to call the default method explicitly. You can call the default method explicitly using below notation.

Syntax
{InterfaceName}.super.{method}

Interface1.java
public interface Interface1 {
    default void print(){
        System.out.println("I am in Interface1");
    }
}

Interface2.java
public interface Interface2 {
     default void print(){
        System.out.println("I am in Interface2");
    }
}


MyClass.java

public class MyClass implements Interface1, Interface2{
 public void print(){
  System.out.println("I am in MyClass");
  Interface1.super.print();
  Interface2.super.print();
 }
}


You may like

No comments:

Post a Comment