
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 Selected Methods of Interface in Java
Once you implement an interface from a concrete class you need to provide implementation to all its methods. If you try to skip implementing methods of an interface at compile time an error would be generated.
Example
interface MyInterface{ public void sample(); public void display(); } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); } }
Compile-time error
InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method display() in MyInterface public class InterfaceExample implements MyInterface{ ^ 1 error
But, If you still need to skip the implementation.
- You can either provide a dummy implementation to the unwanted methods by throwing an exception such as UnsupportedOperationException or, IllegalStateException from them.
Example
interface MyInterface{ public void sample(); public void display(); } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public void display(){ throw new UnsupportedOperationException(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); obj.display(); } }
Output
Implementation of the sample method Exception in thread "main" java.lang.UnsupportedOperationException at InterfaceExample.display(InterfaceExample.java:10) at InterfaceExample.main(InterfaceExample.java:15)
- You can make the methods default in the interface itself, Default methods are introduced in interfaces since Java8 and if you have default methods in an interface it is not mandatory to override them in the implementing class.
Example
interface MyInterface{ public void sample(); default public void display(){ System.out.println("Default implementation of the display method"); } } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); obj.display(); } }
Output
Implementation of the sample method Default implementation of the display method
Advertisements