How to override only few 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

 Live Demo

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

 Live Demo

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

 Live Demo

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
raja
Published on 10-Sep-2019 14:40:33
Advertisements