top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

When can an object reference be cast to an interface reference?

+2 votes
357 views
When can an object reference be cast to an interface reference?
posted Apr 7, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

If I understand your question correctly, usually object references are cast to interface reference if the Class (or Classes) of the object implements interface and the process expects certain properties/methods in class but it need not be the exact class.

Say for an example, I have an interface, two class that implements this interface and an implementation class. Here, in our implementation class, eatNow expects an object that has doEat method and doesn't have to be either Human or Dog, it could even be any class apart from this that implements ILivingThing.

interface ILivingThing {
      void display();
}

public class Human implements ILivingThing {
      public void doTalk() {
           System.out.println(“I am talking”);
      }
      public void doEat() {
           System.out.println(“I am eating”);
      }
}

public class Dog implements ILivingThing {
      public void doBark() {
           System.out.println(“I am barking”);
      }
      public void doEat() {
           System.out.println(“I am eating”);
      }
}

Now, I have an implementation class,

public class MyClass {
     public MyClass() {
          Human h = new Human();
          Dog d = new Dog();
          eatNow(h);  // Both the classes are acceptable parameters
          eatNow(d);
     }

     public eatNow(ILivingThing livingThing) {
          livingThing.doEat();
     }
}

Hope this helps! Let me know if you need any more information.

answer May 19, 2016 by Vinod Kumar K V
...