Is it mandatory to override the default methods of an interface in Java?


The default methods are introduced in an interface since Java8. Unlike other abstract methods these are the methods can have a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface.

In short, you can access the default methods of an interface using the objects of the implementing classes.

Example

interface MyInterface{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}

Output

display method of MyInterface

But, when your class implements two interfaces, and if they both have methods with same name and prototype. You must override this method else a compile time error is generated.

Example

interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      // obj.display();
   }
}

Compile time error

InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2
public class InterfaceExample implements MyInterface1, MyInterface2{
^
1 error

To resolve this you need to override either (or, both) of the display() methods in the implementing class −

Example

interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      MyInterface1.super.display();
      //or,
      MyInterface2.super.display();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}

Output

display method of MyInterface1
display method of MyInterface2
raja
Published on 01-Aug-2019 14:42:37
Advertisements