Analyze the following code, and find output at invocations of tryMe() in main()
ID: 3813648 • Letter: A
Question
Analyze the following code, and find output at invocations of tryMe() in main() as well the justification of the output. Also, find out if each of the commented statements below will result in a compile time error or a run time error, and why?
class Animal{
public void tryMe(){
System.out.println("####");
}
}
class Cat extends Animal {
public void tryMe(){
System.out.println("Meow !");
}
}
class Dog extends Animal{
public void tryMe(){
System.out.println("Bark !");
}
}
public class AnimalTest {
public static void main(String args[]) {
Animal a = new Animal();
Animal c = new Cat();
Dog d = new Dog();
a.tryMe();
c.tryMe();
d.tryMe();
Animal anotherA = ((Animal)d);
anotherA.tryMe();
Dog anotherD = ((Dog)(Animal)d);
anotherD.tryMe();
// anotherD = ((Dog)a);
// anotherA =((Cat)(Animal)d);
// anotherD = ((Cat)(Animal)d);
// Cat anotherC = ((Cat)(Animal)d);
}
}
Explanation / Answer
The Output of this Program is
####
Meow !
Bark !
Bark !
Bark !
Dynamic method dispatch is how java implements runtime polymorphism. When an overridden method is called by a reference,java determines which version of that method to execute based on the type of object it refer to. So the object and not the reference will decide which method will be called in c.tryMe() reference is of type Animal but object is of type Cat so cats method will be called.
Now About UnCommenting Last 4 Lines.
If We Uncomment anotherD = ((Dog)a); it will give run time error as below
Animal cannot be cast to Dog
If We Uncomment anotherA =((Cat)(Animal)d); it will give run time error as below
Dog cannot be cast to Cat
If We Uncomment anotherD = ((Cat)(Animal)d); it will give compile time error as below
incompatible types expected Dog instead of Cat
If We Uncomment Cat anotherC = ((Cat)(Animal)d); it will give run time error as below
Dog cannot be cast to Cat