When can an object reference be cast to an interface reference

An object reference be cast to an interface reference when the object implements the referenced interface.

In Java, an object reference can be cast to an interface reference when the object’s class implements that interface. This is possible because Java supports polymorphism through interfaces. Here’s a brief explanation:

  1. When the Object Implements the Interface: If a class implements an interface, you can cast an object of that class to a reference of the interface type.
    java
    interface MyInterface {
    void myMethod();
    }

    class MyClass implements MyInterface {
    @Override
    public void myMethod() {
    System.out.println("Implementation of myMethod");
    }
    }

    public class Main {
    public static void main(String[] args) {
    MyClass obj = new MyClass();

    // Casting to the interface type
    MyInterface interfaceRef = (MyInterface) obj;

    // Calling the method through the interface reference
    interfaceRef.myMethod();
    }
    }

  2. When Using Inheritance: If a class extends another class and that superclass implements an interface, you can also cast an object of the subclass to a reference of the interface type.
    java
    interface MyInterface {
    void myMethod();
    }

    class MyBaseClass {
    // MyBaseClass implements MyInterface
    public void myMethod() {
    System.out.println("Implementation of myMethod in MyBaseClass");
    }
    }

    class MyDerivedClass extends MyBaseClass {
    // Additional functionality
    }

    public class Main {
    public static void main(String[] args) {
    MyDerivedClass obj = new MyDerivedClass();

    // Casting to the interface type
    MyInterface interfaceRef = (MyInterface) obj;

    // Calling the method through the interface reference
    interfaceRef.myMethod();
    }
    }

In both cases, the key is that the actual class of the object being referred to must implement the interface for the cast to be valid. Otherwise, a ClassCastException will occur at runtime.