Can we override default methods in Java?

JavaServer Side ProgrammingProgramming

An interface in Java is similar to 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. 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

Live Demo

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

Overriding default methods

you can override a default method of an interface from the implementing class.

Example

Live Demo

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

Output

display method of class

raja
Published on 08-Feb-2021 16:17:50
Advertisements