Dynamic Method Dispatch
This program demonstrates dynamic method dispatch.
Problem Statement
Write a Java program to show dynamic method dispatch between superclass and subclass.
Source Code
| 1 | class Animal { |
| 2 | void sound(){ System.out.println("Animal sound"); } |
| 3 | } |
| 4 | class Dog extends Animal { |
| 5 | @Override |
| 6 | void sound(){ System.out.println("Dog barks"); } |
| 7 | } |
| 8 | public class DynamicDispatch { |
| 9 | public static void main(String[] args) { |
| 10 | System.out.println("Eduinq Dynamic Method Dispatch"); |
| 11 | Animal a=new Dog(); |
| 12 | a.sound(); |
| 13 | } |
| 14 | } |
Program Output
Eduinq Dynamic Method Dispatch Dog barks
Explanation
Superclass reference points to subclass object. - At runtime, JVM decides which method to execute. - This is polymorphism in action, enabling flexible code that adapts to object type dynamically. Conclusion: Shows how dynamic method dispatch works in Java.