
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Cast Object Reference to Interface Reference in Java
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
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.