Dynamic Method Dispatch

 

Dynamic Method Dispatch in Java

Dynamic Method Dispatch is a mechanism in Java that determines which version of an overridden method to call at runtime, not compile time. It is the core of runtime polymorphism in Java.


✅ Definition:

Dynamic Method Dispatch refers to the process by which a call to an overridden method is resolved at runtime rather than at compile time.

This happens when a superclass reference is used to refer to a subclass object.


๐Ÿ“˜ Example:

class Animal {
void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal a; // superclass reference a = new Dog(); // subclass object a.sound(); // calls Dog's sound() a = new Cat(); // new subclass object a.sound(); // calls Cat's sound() } }

๐Ÿงพ Output:


Dog barks Cat meows

๐Ÿง  Key Concepts:

ConceptDescription
PolymorphismSame interface, different behaviors
Method OverridingRequired for dynamic dispatch
Superclass referenceRefers to subclass objects
Late Binding (Runtime Binding)The method to execute is selected during program execution

⚠️ Important Notes:

  • Only non-static, non-final, and non-private methods are dynamically dispatched.

  • Constructors are not involved in dynamic dispatch.

  • Static methods are resolved at compile time (called early binding).


๐Ÿงช Real-life Analogy:

Think of a remote control (reference variable of superclass type). You can use the same remote to control a TV, AC, or Fan (objects of different subclasses). What actually happens depends on the object you connect the remote to.


✅ Summary:

  • Dynamic Method Dispatch = deciding at runtime which overridden method to call.

  • Enables runtime polymorphism.

  • Improves flexibility and extensibility in object-oriented design.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism