What happens if we overload default methods of an interface in java?


An interface in Java is similar to a class but, it contains only abstract methods and fields which are final and static.

Since Java8 static methods and default methods are introduced in interfaces.

Default methods − Unlike other abstract methods these are the methods that can have a default implementation. If you have a 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

 Live Demo

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

Output

Default implementation of the display method

Overriding default methods

It is not mandatory to override the default methods of an interface, but still, you can override them like normal methods of a superclass. But, make sure that you remove the default keyword before them.

Example

 Live Demo

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

Output

Hello welcome to Tutorialspoint

Updated on: 10-Sep-2019

998 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements