- Trending Categories
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
Must we implement all the methods in a class that implements an interface in Java?
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
There are only two choices −
- Implement every method defined by the interface.
- Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects.
The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e. non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The subclass may not implement the interface at all and just method signature is matched.
Example
interface MyInterface { void m() throws NullPointerException; } class SuperClass { // SuperClass class doesn't implements MyInterface interface public void m() { System.out.println("Inside SuperClass m()"); } } class SubClass extends SuperClass implements MyInterface { } public class Program { public static void main(String args[]) { SubClass s = new SubClass(); s.m(); } }
Output
Inside SuperClass m()
The above code shows a concrete class SubClass that declares that it implements an interface MyInterface, but doesn't implement the m() method of the interface. The code is legal because it's parent class SuperClass implements a method called m() with the same name as the method in the interface.
- Related Articles
- What happens if a class does not implement all the abstract methods of an interface in java?
- List the Interfaces That a Class Implements in Java
- Can Enum implements an interface in Java?\n
- Can we overload methods of an interface in Java?
- Can we write an interface without any methods in java?
- How to implement an interface using an anonymous inner class in Java?
- Can we use private methods in an interface in Java 9?
- Can we define an interface inside a Java class?
- Why do we need private methods in an interface in Java 9?
- Why an interface cannot implement another interface in Java?
- What happens if we overload default methods of an interface in java?
- How can we implement the Subscriber interface in Java 9?
- Can we implement one interface from another in java?
- How to hide unsupported interface methods from class in Java?
- Can we define a class inside a Java interface?
