- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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