LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · PILLAR · 5 OF 48

Polymorphism in Java: Overloading, Overriding and Dynamic Dispatch

Polymorphism explained with ride fares: one call that behaves differently for each ride type, runtime polymorphism through overriding and dynamic dispatch, compile-time overloading and its trap, why fields and static methods are not polymorphic, and how to replace a growing if-else chain on a type code with classes, with a runnable Java 17 example.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 141 lines, with a small main() demo. Save it as PolymorphismDemo.java, then run javac PolymorphismDemo.java && java PolymorphismDemo.

import java.util.List;

/**
 * Polymorphism with ride fares.
 * Part 1: an if-else chain on a type string (the problem).
 * Part 2: one class per ride type behind RideOption; dynamic dispatch picks the formula.
 * Part 3: overloading is chosen at compile time from the static type.
 */
public class PolymorphismDemo {

    public static void main(String[] args) {
        int km = 8;
        int minutes = 20;

        // ---------- Part 1: the problem ----------
        System.out.println("Type-code fare for MINI: " + TypeCodeFares.fare("MINI", km, minutes));

        // ---------- Part 2: runtime polymorphism ----------
        List<RideOption> rides = List.of(new AutoRide(), new MiniCab(), new SuvRide(), new PoolRide());
        for (RideOption ride : rides) {
            // One call. The JVM runs the method of the real object (dynamic dispatch).
            System.out.println(ride.name() + " fare: " + ride.fare(km, minutes));
        }

        RideOption r = new MiniCab();   // static type RideOption, runtime type MiniCab
        System.out.println("Runtime class of r: " + r.getClass().getSimpleName());

        // ---------- Part 3: compile-time polymorphism (overloading) ----------
        Receipts receipts = new Receipts();
        System.out.println(receipts.print(190));
        System.out.println(receipts.print(190, "FEST10"));
        System.out.println(receipts.print(190, 10));

        Object x = "MINI";
        System.out.println("label(x) with Object x = \"MINI\": " + receipts.label(x));
        System.out.println("label(\"MINI\") directly        : " + receipts.label("MINI"));
    }
}

// ---------- Part 1: the problem ----------

/** The same chain tends to be copied into eta(), icon(), cancelFee()... */
final class TypeCodeFares {
    private TypeCodeFares() {
    }

    static long fare(String type, int km, int min) {
        if (type.equals("AUTO")) {
            return 30 + 12L * km;
        } else if (type.equals("MINI")) {
            return 50 + 15L * km + min;
        } else if (type.equals("SUV")) {
            return Math.max(300, 80 + 22L * km + 2L * min);
        }
        throw new IllegalArgumentException("unknown ride type " + type);
    }
}

// ---------- Part 2: one class per branch ----------

interface RideOption {
    String name();

    long fare(int km, int minutes);
}

class AutoRide implements RideOption {
    @Override
    public String name() {
        return "Auto";
    }

    @Override
    public long fare(int km, int minutes) {
        return 30 + 12L * km;          // autos ignore waiting time here
    }
}

class MiniCab implements RideOption {
    @Override
    public String name() {
        return "Mini";
    }

    @Override
    public long fare(int km, int minutes) {
        return 50 + 15L * km + minutes;
    }
}

class SuvRide implements RideOption {
    private static final long MINIMUM = 300;

    @Override
    public String name() {
        return "SUV";
    }

    @Override
    public long fare(int km, int minutes) {
        return Math.max(MINIMUM, 80 + 22L * km + 2L * minutes);
    }
}

/** Added later: a new class, and no existing caller was edited. */
class PoolRide implements RideOption {
    @Override
    public String name() {
        return "Pool";
    }

    @Override
    public long fare(int km, int minutes) {
        return 35 + 9L * km;
    }
}

// ---------- Part 3: overloading ----------

class Receipts {
    String print(long fare) {
        return "Total: " + fare;
    }

    String print(long fare, String coupon) {
        return "Total: " + fare + " (coupon " + coupon + " applied at payment)";
    }

    String print(long fare, int tipPercent) {
        return "Total: " + (fare + fare * tipPercent / 100) + " incl. " + tipPercent + "% tip";
    }

    // Overloads are picked by the STATIC type of the argument.
    String label(Object o) {
        return "object";
    }

    String label(String s) {
        return "text";
    }
}

Notes

The problem

Here is a fare calculator in a ride app. It checks a type string: auto, mini or S U V, and runs a different formula for each. It works, but the same chain appears again in the code for arrival time, map icon, cancel fee and seat count. Adding a pool ride means finding and editing every chain, and missing one is a bug that only shows up when someone books a pool ride.

Fare by type code
long fare(String type, int km, int min) {
  if (type.equals("AUTO"))
    return 30 + 12 * km;
  else if (type.equals("MINI"))
    return 50 + 15 * km + min;
  else if (type.equals("SUV"))
    return Math.max(300, 80+22*km+2*min);
  throw new IllegalArgumentException(type);
}
// same chain again in eta(), icon(),
// cancelFee(), seats() ...

The idea

Polymorphism means code written against one type works with many types, and each object decides how to respond. The booking service just says: ride, what is your fare for eight kilometres and twenty minutes? It never asks which kind of ride it is. The object already knows what it is, so the decision moves from a chain of checks into the objects themselves.

In one sentence
  • polymorphism: code written
  • against one type works with
  • many types, and each object
  • decides how to respond
  • caller says: ride.fare(8, 20)
  • it never asks "which ride?"
  • the object already knows

The structure

Each branch of the old chain becomes a class. The RideOption interface declares fare. Auto ride returns thirty plus twelve per kilometre. Mini cab adds a per minute charge. S U V ride applies a minimum fare of three hundred. Each formula lives with its ride type, and the related methods, like arrival time or cancel fee, can live there too. No more string type codes.

One class per branch
interface RideOption {
  String name();
  long fare(int km, int minutes);
}
class AutoRide implements RideOption {
  public long fare(int km, int min) {
    return 30 + 12L * km;
  }
}
// MiniCab, SuvRide: their own formula

Run-through

The booking service loops over the available rides and calls fare with eight kilometres and twenty minutes. The auto answers one hundred and twenty six. The mini cab answers one hundred and ninety. The S U V works out two hundred and ninety six, then lifts it to its minimum of three hundred. The calling code is the same single line each time.

Dynamic dispatch

How does Java know which fare to run? A variable has a static type, here RideOption, which the compiler checks. The object has a runtime type, here mini cab. The compiler only confirms that RideOption has a fare method. When the program runs, the virtual machine looks at the actual object and calls mini cab's version. This is dynamic dispatch, also called late binding.

How Java picks
RideOption r = new MiniCab();
//  static type: RideOption
//  runtime type: MiniCab

r.fare(8, 20);
// compiler: does RideOption
//   have fare(int, int)? yes
// at runtime: run MiniCab.fare

this is called late binding

Adding a type

Now add a pool ride. Write one new class, pool ride, that implements RideOption with its own cheaper formula, and add it where the list of rides is built. The booking service, the receipts and every other caller stay exactly as they were. Compare that with hunting down every if else chain. This is also the open closed principle, which the SOLID unit covers next.

Overloading

The other kind is compile time polymorphism, or overloading. A class has several methods with the same name but different parameter lists. Receipts can print a fare, a fare with a coupon, or a fare with a tip percentage. The compiler picks the version from the number and types of the arguments, before the program ever runs. The return type alone cannot tell overloads apart.

Compile-time polymorphism
String print(long fare)
String print(long fare, String coupon)
String print(long fare, int tipPercent)

print(190)            // first
print(190, "FEST10")   // second
print(190, 10)         // third

chosen at compile time from
the argument types

The overloading trap

Here is the trap that appears in interviews. Two overloads: label taking an Object and label taking a String. A variable of type Object holds the text MINI. Calling label picks the Object version, because overloads are chosen at compile time from the static type of the variable. Only overriding looks at the real object at runtime. Mixing up the two is a classic source of bugs.

Surprise
String label(Object o) { return "obj"; }
String label(String s) { return "text"; }

Object x = "MINI";
label(x);   // "obj", not "text"!

overloading: static type decides
overriding: runtime type decides

Not polymorphic

Some things do not behave polymorphically. A field with the same name in a parent and a child is hidden, not overridden, and the variable type decides which one you read. Static methods belong to the class and are chosen by the class name. Private methods cannot be overridden at all. Only non private, non static instance methods are dispatched on the runtime type.

What does NOT dispatch
  • fields: picked by the
  • variable type (hiding)
  • static methods: by the
  • class name, not the object
  • private methods: not
  • inherited, never overridden
  • constructors: not inherited
  • only instance methods
  • are dynamically dispatched

Casting is a smell

When you see code that asks, is this ride an S U V, and casts it to add a surcharge, the decision has leaked back to the caller. Instead, put the surcharge inside the S U V class, so the caller can just ask for the fare. A few type checks are fine at the edges, such as reading input, but in the core logic they usually mean a method is missing.

Smell vs fix
// smell
if (r instanceof SuvRide s)
  fare = s.fare(km, min) + 50;

// fix: ask the object
fare = r.fare(km, min);

// SuvRide adds its own surcharge

In the JDK

You use polymorphism all the time. A List variable can hold an ArrayList or a LinkedList, and add works for both. Printing any object calls the real class's toString. A Comparator has one compare method but endless orderings, and a thread runs any Runnable without knowing what it does. Each time, the caller writes against one type, and the objects provide the behaviour.

You already rely on it
  • List l = new ArrayList<>()
  • or new LinkedList<>()
  • println(obj) calls the real
  • toString() of any object
  • Comparator: one compare(),
  • many orderings
  • Runnable: one run(),
  • any task for a thread

When not to

Polymorphism is not always the answer. If there are three fixed values, used in one place, a simple switch is clear and short. Classes win when new types keep arriving, or when several methods switch on the same type code. An enum with a method per constant is a good middle ground: each constant carries its own behaviour, and the compiler knows every possible value.

Do not overdo it
  • classes win when:
  • types keep being added
  • several methods switch on
  • the same type code
  • a switch is fine when:
  • values are fixed and few
  • one place uses them
  • an enum with methods is a
  • good middle ground

In interviews

In design rounds, polymorphism is the answer to almost every if else chain on a type. Parking fees by vehicle, payment methods, notification channels, the moves of chess pieces, and the states of a vending machine. When you see a type code, turn each branch into a class behind one interface. The usual mistakes are instanceof chains in core logic and confusing overloading with overriding.

Where it shows up
  • parking: fee per vehicle
  • payments: card, UPI, wallet
  • notifications: SMS, email
  • chess: each piece moves
  • in its own way
  • vending: state per stage
  • mistake: instanceof chains
  • in the core logic

Interview questions

What is polymorphism?

Polymorphism is the ability of one interface or call to work with objects of different types, each responding in its own way. In Java the caller holds a reference of a supertype, and the method that runs depends on the actual object.

What is the difference between overloading and overriding?

Overloading means several methods in a class share a name but have different parameter lists; the compiler chooses one from the static argument types. Overriding means a subclass replaces an inherited instance method with the same signature; the JVM chooses it at runtime from the object's actual class.

What is dynamic dispatch?

Dynamic dispatch, or late binding, is the runtime mechanism that selects which overridden method to call based on the actual class of the object, not the declared type of the variable. The compiler only checks that the declared type has a matching method.

Can static methods be overridden?

No. A static method with the same signature in a subclass hides the parent's method rather than overriding it. Which one runs depends on the type used at compile time, not on the runtime object, so there is no dynamic dispatch.

Can you overload a method by changing only the return type?

No. Overloads must differ in their parameter lists. The compiler chooses an overload from the arguments at the call site, so two methods that differ only in return type would be ambiguous and do not compile.

How does polymorphism help replace if-else chains?

Each branch of a chain on a type code becomes a class implementing a shared interface, and the caller just calls the method. New types are added as new classes without editing existing callers, and related behaviour stays together in one class.

Are fields polymorphic in Java?

No. If a subclass declares a field with the same name as a parent field, it hides the parent field. Accessing the field through a variable uses the variable's declared type, which is one reason fields should be private and accessed through methods.

What is the output when an overloaded method is called with an Object variable holding a String?

The overload taking Object is chosen, because overload resolution uses the static type of the argument expression, which is Object. Only overridden instance methods look at the runtime type.