Can we cast an object reference to an interface reference in java? If so when?

Java 8Object Oriented ProgrammingProgramming

Yes, you can.

If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

But, using this you can access the methods of the interface only, if you try to access the methods of the class a compile time error is generated.

Example

In the following Java example, we have an interface named MyInterface with an abstract method display().

We have a class with name InterfaceExample with a method (show()). In addition to it, we are implementing the display() method of the interface.

In the main method we are assigning the object of the class to the reference variable of the interface and trying to invoke both the method.

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();
   }
}

Compile time error

On compiling, the above program generates the following compile time error −

InterfaceExample.java:16: error: cannot find symbol
   obj.show();
      ^
symbol: method show()
location: variable obj of type MyInterface
1 error

To make this program work you need to remove the line calling the method of the class as −

Example

 Live Demo

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();
   }
}

Now, the program gets compiled and executed successfully.

Output

This is the implementation of the display method

Therefore, you need to cast an object reference to an interface reference. Whenever you need to call the methods of the interface only.

raja
Updated on 30-Jul-2019 22:30:26

Advertisements