How to hide unsupported interface methods from class in Java?


Actually you can’t, once you implement an interface it is a must to provide implementation to all its methods or, make the class abstract. There is no way to skip methods of an interface without implementing (unless they are default methods). Still, if you try to skip implementing methods of an interface a compile-time error would be generated.

Example

 Live Demo

interface MyInterface{
   public static int num = 100;
   public void sample();
   public void getDetails();
   public void setNumber(int num);
   public void setString(String data);
}
public class InterfaceExample implements MyInterface{
   public static int num = 10000;
   public void sample() {
      System.out.println("This is the implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
   }
}

Output

Compile-time error

InterfaceExample.java:8: error: InterfaceExample is not abstract and does not override abstract method setString(String) in MyInterface
public class InterfaceExample implements MyInterface{
      ^
1 error

But, you can implement these unwanted/unsupported methods and throw an exception such as UnsupportedOperationException or, IllegalStateException from them.

Example

 Live Demo

interface MyInterface{
   public void sample();
   public void getDetails();
   public void setNumber(int num);
   public void setString(String data);
}
public class InterfaceExample implements MyInterface{
   public void getDetails() {
      try {
         throw new UnsupportedOperationException();
      }
      catch(UnsupportedOperationException ex) {
         System.out.println("Method not supported");
      }
   }
   public void setNumber(int num) {
      try {
         throw new UnsupportedOperationException();
      }
      catch(UnsupportedOperationException ex) {
         System.out.println("Method not supported");
      }
   }
   public void setString(String data) {
      try {
         throw new UnsupportedOperationException();
      }
      catch(UnsupportedOperationException ex) {
         System.out.println("Method not supported");
      }
   }
   public void sample() {
      System.out.println("This is the implementation of the sample method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.sample();
      obj.getDetails();
      obj.setNumber(21);
      obj.setString("data");
   }
}

Output

This is the implementation of the sample method
Method not supported
Method not supported
Method not supported
raja
Published on 10-Sep-2019 14:19:39
Advertisements