Home > Blockchain >  How to call a class function which is not in interface in java
How to call a class function which is not in interface in java

Time:05-26

interface MyInterface{
   public static int num = 100;
   public void display();
}
public class InterfaceExample implements MyInterface{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      System.out.println("This is the implementation of the show method");
   }
   public static void main(String args[]) {
      MyInterface obj = new InterfaceExample();
      obj.display();
      obj.show(); // how can i call this ?
   }
}

Above is some lines of code , I wanted to know can I call show() method of InterFaceExample class using interface object?. Please help.

CodePudding user response:

You have three options.

  1. Add the show method to the interface.
  2. Change the type of obj to InterfaceExample.
  3. Cast obj when you want to use a method that's only in InterfaceExample, for example ((InterfaceExample) obj).show();

The third option here throws an exception if obj happens not to refer to an object of type InterfaceExample.

CodePudding user response:

You need to have an InterfaceExample reference and not a MyInterface reference. The clean way to achieve that is to not assign the InterfaceExample reference to a MyInterface variable; you're throwing type information away. Use an InterfaceExample variable instead.

Alternatively,if there's some reason you have to have a MyInterface variable, then you can cast to an InterfaceExample. You may or may not need to handle the possible resulting exception.

  • Related