Exercise 1
Given Animal a = new Cat();, what determines which method executes when a.eat() is invoked?
Show solution ↓Hide solution ↑
Solution
The actual runtime object type (Cat) determines which method executes via dynamic method dispatch.
Polymorphism (“many forms”) allows a reference variable of a supertype to reference objects of any of its subtypes at runtime:
Animal myPet = new Dog();
myPet.makeSound(); // Invokes Dog's overridden makeSound()
In the declaration above:
Animal. The compiler verifies that makeSound() is a valid method on Animal.Dog. At runtime, the JVM inspects the actual object on the heap.When an overridden method is called, Java uses dynamic method dispatch (late binding) to execute the method belonging to the actual runtime object, not the declared variable type.
@Override).Given Animal a = new Cat();, what determines which method executes when a.eat() is invoked?
The actual runtime object type (Cat) determines which method executes via dynamic method dispatch.