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.

raja
Published on 22-May-2019 15:21:58
Advertisements