Can super class reference variable can hold an object of sub class?
Yes. Look at the example below:
Actor reference variables actor1, actor2 hold the reference of objects of sub classes of Animal, Comedian and Hero.
Since object is super class of all classes, an Object reference variable can also hold an instance of any class.
//Object is super class of all java classes
Object object = new Hero();
public class Actor {
public void act(){
System.out.println("Act");
};
}
//IS-A relationship. Hero is-a Actor public class Hero extends Actor { public void fight(){ System.out.println("fight"); }; } |
//IS-A relationship. Comedian is-a Actor public class Comedian extends Actor { public void performComedy(){ System.out.println("Comedy"); }; } |
Actor actor1 = new Comedian();
Actor actor2 = new Hero();
No Comments Yet!!