Dynamic method dispatch
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A variable of type Payment can hold a UPI payment or a card payment. When you call pay(), who decides which version runs, and when?
How the JVM picks the method
Dynamic method dispatch is the process by which the JVM decides at run time which overridden method a call runs, by looking at the class of the actual object, not the reference type. It is how Java achieves runtime polymorphism.
Dispatch means sending a call to the right method; dynamic means it happens while the program runs. One Animal variable can point to different objects over time.
Example 1 · One variable, different objects
class Animal { void sound() { System.out.println("Some sound"); }}
class Dog extends Animal { @Override void sound() { System.out.println("Bark"); }}
class Cat extends Animal { @Override void sound() { System.out.println("Meow"); }}
public class DispatchDemo { public static void main(String[] args) { Animal a = new Dog(); a.sound(); a = new Cat(); a.sound(); a = new Animal(); a.sound(); }}Bark Meow Some sound
What this code does
- The line
a.sound()is the same three times, andais always anAnimalvariable. - Each time, the JVM checks which object
apoints to right now and runs that class's version.
The work is split in two. At compile time, javac checks that the reference type has the method, or the line does not compile. At run time, the JVM looks at the object and runs its version. It is also called late binding.
The search walks up the class tree
The JVM starts at the object's own class. If that class has no version of the method, it moves up one parent at a time and runs the first version it finds.
Example 2 · The search walks up
class Vehicle { void fuel() { System.out.println("Vehicle: any fuel"); }}
class Car extends Vehicle { @Override void fuel() { System.out.println("Car: petrol"); }}
class SportsCar extends Car {}
public class SearchDemo { public static void main(String[] args) { Vehicle v = new SportsCar(); v.fuel(); }}Car: petrol
What this code does
- The object is a
SportsCar, which has nofuel(). The JVM moves up toCarand finds one there. Vehicle's version is never reached, becauseCar's version is found first.
So the version that runs is the closest one above the object, never one below it and never one in a sibling class.
A parent method calls the child's version
A call made inside a parent method is dispatched too. If print() in Report calls title(), and the object is a MarksReport, the child's title() runs.
Example 3 · A parent method, a child step
class Exam { void result(String name, int marks) { System.out.println(name + ": " + marks + " -> " + grade(marks)); }
String grade(int marks) { return marks >= 35 ? "Pass" : "Fail"; }}
class Olympiad extends Exam { @Override String grade(int marks) { return marks >= 90 ? "Gold" : "Participation"; }}
public class GradeDemo { public static void main(String[] args) { Exam[] exams = { new Exam(), new Olympiad(), new Olympiad() }; String[] names = { "Rohan", "Diya", "Arjun" }; int[] marks = { 41, 94, 72 }; for (int i = 0; i < exams.length; i++) { exams[i].result(names[i], marks[i]); } }}Rohan: 41 -> Pass Diya: 94 -> Gold Arjun: 72 -> Participation
What this code does
result()is written only inExam. Its callgrade(marks)is made on the current object.- For an
Olympiadobject, that call is dispatched to theOlympiadoverride, so the sameresult()gives different grades.
This is a common pattern: the parent method holds the steps that never change, and children override the one step that differs.
Trace the code
Which title() runs?
Variables
- r
- Report object
Output
(nothing printed yet)Line 18r points to a plain Report object.
What is not dispatched
Only overridden instance methods are dispatched. Fields, static methods and private methods are fixed by the compiler from the reference type.
Example 4 · Fields and static methods follow the reference type
class Bank { String name = "Bank";
static void info() { System.out.println("Bank rules"); }
void greet() { System.out.println("Welcome to the bank"); }}
class StudentBank extends Bank { String name = "StudentBank";
static void info() { System.out.println("Student bank rules"); }
@Override void greet() { System.out.println("Welcome, student"); }}
public class NotDispatchedDemo { public static void main(String[] args) { Bank b = new StudentBank(); b.greet(); System.out.println(b.name); b.info(); }}Welcome, student Bank Bank rules
What this code does
greet()is an overridden instance method, so theStudentBankobject decides.b.nameis a field andb.info()isstatic: the compiler fixes both from the reference typeBank.- The object has two
namefields and the class has twoinfo()methods; nothing is replaced, so this is confusing. Avoid it.
So never give a child a field with the parent's field name; read values that differ per child through an overridden method instead. Field hiding vs method overriding (opens in a new tab) looks at both cases in detail.
static methods with the class name, Bank.info(), so it is clear that no object is involved.Example 5 · Full example: a payment counter
class Payment { String name() { return "Cash"; }
int fee(int amount) { return 0; }
int pay(int amount) { int total = amount + fee(amount); System.out.println(name() + ": Rs. " + amount + " + fee Rs. " + fee(amount) + " = Rs. " + total); return total; }}
class CardPayment extends Payment { @Override String name() { return "Card"; }
@Override int fee(int amount) { return amount * 2 / 100; }}
class NetBanking extends Payment { @Override String name() { return "NetBanking"; }
@Override int fee(int amount) { return 10; }}
public class CounterDemo { public static void main(String[] args) { Payment[] payments = { new Payment(), new CardPayment(), new NetBanking() }; int[] amounts = { 200, 1500, 800 }; int collected = 0; for (int i = 0; i < payments.length; i++) { collected = collected + payments[i].pay(amounts[i]); } System.out.println("Collected: Rs. " + collected); }}Cash: Rs. 200 + fee Rs. 0 = Rs. 200 Card: Rs. 1500 + fee Rs. 30 = Rs. 1530 NetBanking: Rs. 800 + fee Rs. 10 = Rs. 810 Collected: Rs. 2540
What this code does
pay()is written once, inPayment. Its calls toname()andfee()are dispatched to each object's own versions.- A new payment type needs only a new class with
name()andfee(). The loop andpay()do not change.
Next step
Check your understanding
12 quick questions