
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Override Default Methods in Java
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
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
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
Advertisements