Skip to lesson

Dynamic method dispatch

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

DispatchDemo.javaJava
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();    }}
Output
Bark
Meow
Some sound

What this code does

  • The line a.sound() is the same three times, and a is always an Animal variable.
  • Each time, the JVM checks which object a points 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

SearchDemo.javaJava
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();    }}
Output
Car: petrol

What this code does

  • The object is a SportsCar, which has no fuel(). The JVM moves up to Car and finds one there.
  • Vehicle's version is never reached, because Car'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

GradeDemo.javaJava
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]);        }    }}
Output
Rohan: 41 -> Pass
Diya: 94 -> Gold
Arjun: 72 -> Participation

What this code does

  • result() is written only in Exam. Its call grade(marks) is made on the current object.
  • For an Olympiad object, that call is dispatched to the Olympiad override, so the same result() 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?

class Report {
void print() {
System.out.println("== " + title() + " ==");
System.out.println("Class 10-B");
}
String title() {
return "Report";
}
}
class MarksReport extends Report {
@Override
String title() {
return "Marks: Priya";
}
}
public class TemplateTrace {
public static void main(String[] args) {
Report r = new Report();
r.print();
r = new MarksReport();
r.print();
}
}

Variables

r
Report object

Output

(nothing printed yet)

Line 18r points to a plain Report object.

Step 1 of 10

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

NotDispatchedDemo.javaJava
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();    }}
Output
Welcome, student
Bank
Bank rules

What this code does

  • greet() is an overridden instance method, so the StudentBank object decides.
  • b.name is a field and b.info() is static: the compiler fixes both from the reference type Bank.
  • The object has two name fields and the class has two info() 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.

Call static methods with the class name, Bank.info(), so it is clear that no object is involved.

Example 5 · Full example: a payment counter

CounterDemo.javaJava
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);    }}
Output
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, in Payment. Its calls to name() and fee() are dispatched to each object's own versions.
  • A new payment type needs only a new class with name() and fee(). The loop and pay() do not change.

Next step

Check your understanding

12 quick questions