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.
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(); } }
Default implementation of the display method
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.
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(); } }
Hello welcome to Tutorialspoint