SyntaxPilot
Courses/Low-Level Design/Lesson 9

Low-Level Design · Lesson 9 of 90 · 11 min

OOP 4: polymorphism

polymorphismcompile-time polymorphismmethod overloadingruntime polymorphismmethod overridingdynamic dispatchvirtual methodsupcastingdowncastinginstanceofpattern matching for instanceofswitch pattern matchingcovariant return typesreplacing conditionals with polymorphism

These are the notes for Low-Level Design (LLD) episode 9, the fourth and last pillar of object-oriented programming. We build the fee counter of a mall parking lot and turn a fragile type switch into an extendable design: polymorphism, runtime polymorphism with method overriding, dynamic dispatch and virtual methods, compile-time polymorphism with method overloading (and its trap), upcasting and downcasting, instanceof, pattern matching for instanceof, switch pattern matching, covariant return types, and replacing conditionals with polymorphism. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.

1. The problem: a switch on a type code

A mall parking lot charges bikes Rs 10/hour, cars Rs 30/hour, trucks Rs 80/hour. Then it adds EV (electric vehicle) bays at Rs 20/hour, and nobody updates the fee code.

class Vehicle {
    final String type, plate;
    Vehicle(String t, String p) { type = t; plate = p; }
}
class ParkingLot {
    int fee(Vehicle v, int hours) {
        switch (v.type) {
            case "BIKE": return 10 * hours;
            case "CAR": return 30 * hours;
            case "TRUCK": return 80 * hours;
            default: return 0;
        }
    }
}
public class Main {
    public static void main(String[] args) {
        ParkingLot lot = new ParkingLot();
        Vehicle[] today = { new Vehicle("BIKE", "KA01"),
            new Vehicle("CAR", "KA02"), new Vehicle("EV", "KA03") };
        for (Vehicle v : today)
            System.out.println(v.type + ": Rs " + lot.fee(v, 3));
    }
}
BIKE: Rs 30
CAR: Rs 90
EV: Rs 0

The EV parked for free, with no error. A switch picks a branch by matching a value against each case. Here it switches on a type code: a string (or number) that stands for a kind of object. The knowledge of how each vehicle is charged lives outside the vehicle, so:

  • every switch on the type code (fees, receipts, parking level, reports...) must be found and updated for every new kind;
  • a forgotten case or a typo ("Ev" vs "EV") quietly falls into default.

2. Polymorphism and runtime polymorphism

At the exit gate the guard says the same thing to everyone, "please pay", and each driver pays their own rate. The guard never checks the vehicle type.

At the exit gate In Java
The guard says one thing: "please pay" One call: v.fee(3)
Each driver knows their own rate Many behaviours: each class's own fee()
The guard never asks the type Polymorphism ("many forms")

Polymorphism means one call, written once, that behaves differently depending on which object receives it.

abstract class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
    abstract int fee(int hours);
}
class Bike extends Vehicle {
    Bike(String plate) { super(plate); }
    @Override int fee(int hours) { return 10 * hours; }
}
class Car extends Vehicle {
    Car(String plate) { super(plate); }
    @Override int fee(int hours) { return 30 * hours; }
}
class Ev extends Vehicle {
    Ev(String plate) { super(plate); }
    @Override int fee(int hours) { return 20 * hours; }
}
public class Main {
    public static void main(String[] args) {
        Vehicle[] today = { new Bike("KA01"),
            new Car("KA02"), new Ev("KA03") };
        for (Vehicle v : today)
            System.out.println(v.plate + ": Rs " + v.fee(3));
    }
}
KA01: Rs 30
KA02: Rs 90
KA03: Rs 60
  • Vehicle is abstract with an abstract int fee(int hours): every vehicle must answer.
  • Each subclass overrides fee (episode 8) with @Override.
  • The loop makes one call, v.fee(3). A new vehicle type is one new class; forgetting fee in it is a compile error (... is not abstract and does not override abstract method fee(int) in Vehicle), not free parking.

This is runtime polymorphism: the method that runs is chosen while the program runs.

3. Dynamic dispatch and virtual methods

Vehicle v = new Ev("KA03");
v.fee(3);
Declared type (left side) Actual object (after new)
Here Vehicle Ev
Decides what you may call (checked at compile time) which code runs (chosen at run time)
  1. Compile time: the compiler checks only the declared type. Does Vehicle have fee(int)? Yes, so it compiles.
  2. Run time: the JVM looks at the actual object, sees an Ev, and runs Ev.fee.

Choosing the method by the actual object at run time is dynamic dispatch. Methods chosen this way are virtual methods. In Java every instance method is virtual except static, private and final methods (they can't be overridden, so the compiler can fix the choice early). Fields are not polymorphic: v.someField always uses the declared type.

4. Compile-time polymorphism: method overloading

Method overloading: several methods with the same name but different parameter lists (number, types or order of parameters). The compiler picks one from the types of the arguments, before the program runs, so it's called compile-time polymorphism (or static polymorphism).

public class Main {
    static void print(int amount) {
        System.out.println("Paid Rs " + amount);
    }
    static void print(String plate, int amount) {
        System.out.println(plate + " paid Rs " + amount);
    }
    static void print(double amount) {
        System.out.printf("Paid Rs %.2f%n", amount);
    }
    public static void main(String[] args) {
        print(90);
        print("KA02", 90);
        print(45.5);
    }
}
Paid Rs 90
KA02 paid Rs 90
Paid Rs 45.50

%.2f in printf prints a decimal number with 2 digits after the point; %n is a newline. A double is a number with a decimal part.

Overloads must differ in parameters; a different return type alone is not enough. Ambiguous calls don't compile:

public class Main {
    static void pay(int rupees, long paise) { System.out.println("A"); }
    static void pay(long rupees, int paise) { System.out.println("B"); }
    public static void main(String[] args) {
        pay(1, 2);
    }
}

Output:

Main.java:5: error: reference to pay is ambiguous
        pay(1, 2);
        ^
  both method pay(int,long) in Main and method pay(long,int) in Main match
1 error

5. The overloading trap

class Vehicle { }
class Car extends Vehicle { }
public class Main {
    static String welcome(Vehicle v) { return "Welcome, vehicle: level 1"; }
    static String welcome(Car c) { return "Welcome, car: level 2"; }
    public static void main(String[] args) {
        Car c = new Car();
        Vehicle v = c;   // the SAME car
        System.out.println(welcome(c));
        System.out.println(welcome(v));
    }
}
Welcome, car: level 2
Welcome, vehicle: level 1

The same object got two different answers. Overloading is resolved at compile time using the declared type of the argument: c is declared Car, v is declared Vehicle. The actual object is never looked at. Overriding is the opposite.

Overloading Overriding
Also called Compile-time (static) polymorphism Runtime (dynamic) polymorphism
Same name? Yes Yes
Parameters Different Same
Where Same class (or inherited) Subclass
Chosen by Compiler JVM, at run time
Uses Declared types of arguments Actual class of the receiving object
Example print(int), print(String, int) Vehicle.fee(), Ev.fee()

6. Upcasting and downcasting

Casting means telling Java to treat a value as a different type.

At the mall In Java
Any car is a vehicle; the gate lets it in as one Upcasting: Vehicle v = new Car("KA02"); automatic and always safe
The valet desk handles cars only Downcasting: Car c = (Car) v; you promise it's a Car
A bike reaches the valet ClassCastException at run time
abstract class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
}
class Bike extends Vehicle {
    Bike(String plate) { super(plate); }
}
class Car extends Vehicle {
    Car(String plate) { super(plate); }
    String valet() { return "valet parks " + plate; }
}
public class Main {
    public static void main(String[] args) {
        Vehicle[] today = { new Car("KA02"), new Bike("KA01") };
        for (Vehicle v : today) {
            Car c = (Car) v;
            System.out.println(c.valet());
        }
    }
}
valet parks KA02
Exception in thread "main" java.lang.ClassCastException: class Bike cannot be cast to class Car (Bike and Car are in unnamed module of loader 'app')
    at Main.main(Main.java:16)

It compiled (the compiler trusts your cast) and crashed at run time on the bike. Without the cast it wouldn't even compile: error: incompatible types: Vehicle cannot be converted to Car.

7. instanceof and pattern matching for instanceof

The instanceof operator asks "is this object an instance of this class (or a subclass of it)?" and returns true or false. Old style:

if (v instanceof Car) {
    Car c = (Car) v;
    System.out.println(c.valet());
}

Pattern matching for instanceof (a permanent feature since Java 16, JEP 394) tests and names the variable in one go: v instanceof Car c. If true, c is ready to use as a Car.

abstract class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
}
class Bike extends Vehicle {
    Bike(String plate) { super(plate); }
}
class Car extends Vehicle {
    Car(String plate) { super(plate); }
    String valet() { return "valet parks " + plate; }
}
public class Main {
    public static void main(String[] args) {
        Vehicle[] today = { new Car("KA02"), new Bike("KA01") };
        for (Vehicle v : today) {
            if (v instanceof Car c) System.out.println(c.valet());
            else System.out.println(v.plate + ": self parking");
        }
    }
}
valet parks KA02
KA01: self parking

Use instanceof at the edges, when you genuinely need a subclass's extra method. An instanceof chain repeated around the code is a type switch in disguise; prefer overriding.

8. Switch pattern matching with sealed types

Sometimes an operation belongs outside the classes (for example, the parking lot's pricing policy, which changes more often than the vehicles). Switch pattern matching (permanent since Java 21, JEP 441) lets a switch match on an object's type and name it. Combined with a sealed interface (episode 8), the compiler knows every possible kind, so it can check that the switch is exhaustive (handles every case). A record (episode 3) is a compact, immutable data class.

sealed interface Vehicle permits Bike, Car, Truck { }
record Bike(String plate) implements Vehicle { }
record Car(String plate, boolean ev) implements Vehicle { }
record Truck(String plate, int axles) implements Vehicle { }
public class Main {
    static int fee(Vehicle v, int hours) {
        return switch (v) {
            case Bike b -> 10 * hours;
            case Car c -> (c.ev() ? 20 : 30) * hours;
        };
    }
    public static void main(String[] args) {
        System.out.println(fee(new Car("KA03", true), 3));
        System.out.println(fee(new Truck("KA09", 3), 3));
    }
}
Main.java:7: error: the switch expression does not cover all possible input values
        return switch (v) {
               ^
1 error
sealed interface Vehicle permits Bike, Car, Truck { }
record Bike(String plate) implements Vehicle { }
record Car(String plate, boolean ev) implements Vehicle { }
record Truck(String plate, int axles) implements Vehicle { }
public class Main {
    static int fee(Vehicle v, int hours) {
        return switch (v) {
            case Bike b -> 10 * hours;
            case Car c -> (c.ev() ? 20 : 30) * hours;
            case Truck t -> 40 * t.axles() * hours;
        };
    }
    public static void main(String[] args) {
        System.out.println(fee(new Car("KA03", true), 3));
        System.out.println(fee(new Truck("KA09", 3), 3));
    }
}
60
360

case Car c -> ... is an arrow case: no fall-through, no break needed, and the whole switch is an expression that returns a value. Compare the first switch in section 1, which charged Rs 0 silently.

Which to choose?

Use overriding (polymorphism) when Use a sealed type + exhaustive switch when
The behaviour belongs to each class (a vehicle's own fee) The operation belongs outside a closed family (a pricing policy, a report)
New kinds are added often New operations are added often, kinds rarely
You want one call site, no type checks You want the compiler to list every kind for each operation

9. Covariant return types

class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
    Vehicle copy() { return new Vehicle(plate); }
}
class Car extends Vehicle {
    Car(String plate) { super(plate); }
    @Override Vehicle copy() { return new Car(plate); }
    String valet() { return "valet parks " + plate; }
}
public class Main {
    public static void main(String[] args) {
        Car spare = new Car("KA02").copy();
        System.out.println(spare.valet());
    }
}
Main.java:13: error: incompatible types: Vehicle cannot be converted to Car
        Car spare = new Car("KA02").copy();
                                        ^
1 error

Car.copy() really returns a Car, but its declared return type only promises a Vehicle. An override may narrow its return type to a subclass:

class Vehicle {
    final String plate;
    Vehicle(String plate) { this.plate = plate; }
    Vehicle copy() { return new Vehicle(plate); }
}
class Car extends Vehicle {
    Car(String plate) { super(plate); }
    @Override Car copy() { return new Car(plate); }
    String valet() { return "valet parks " + plate; }
}
public class Main {
    public static void main(String[] args) {
        Car spare = new Car("KA02").copy();
        System.out.println(spare.valet());
    }
}
valet parks KA02

A return type that narrows together with the class in an override is a covariant return type ("varies in the same direction"). It saves callers a cast. Parameter types can't change this way; changing a parameter type makes it an overload, not an override.

10. Replace conditional with polymorphism

A switch/if-else chain on a type code, repeated across the code, is a known code smell (a sign of a design problem). The standard refactoring (a change to structure that keeps behaviour) is replace conditional with polymorphism:

  1. Create an abstract method (or interface method) for the varying behaviour: abstract int fee(int hours).
  2. Create one subclass per type code value and move each branch into its override.
  3. Replace the switch with one call: v.fee(hours).
  4. Delete the type code field.
Conditional on a type code Polymorphism
switch (v.type) { case "BIKE": ... default: return 0; } abstract int fee(int h); per class
Every new type = find every switch Every new type = one new class
Forgotten case = silent bug Forgotten override = compile error

The class diagram

ParkingLot - - - v.fee(h) - - -> «abstract» Vehicle
                                  # plate: String
                                  + fee(hours): int {abstract}
                                  + copy(): Vehicle
                                ^          ^           ^
                             Bike         Car          Ev
                         + fee()     + fee()        + fee()
                                     + copy(): Car
                                     + valet()

Common mistakes

Mistake Exact message Why Fix
Type-code switch with a default no error: EV: Rs 0 Nobody updated the switch Override fee() in each class
Expecting overloads to use the actual object no error: Welcome, vehicle: level 1 Overloading uses declared types Use overriding, or call with the right declared type
Ambiguous overloads error: reference to pay is ambiguous Two overloads fit equally Make parameter lists clearly different
Blind downcast java.lang.ClassCastException: class Bike cannot be cast to class Car The object isn't a Car if (v instanceof Car c)
Assigning a supertype to a subtype error: incompatible types: Vehicle cannot be converted to Car Needs a cast or a covariant return Covariant return, or a checked cast
Pattern switch missing a sealed subtype error: the switch expression does not cover all possible input values Not exhaustive Add the missing case

Mini project

Build a ride receipt printer for a cab app. Ride kinds: Regular(km), Shared(km, riders), Rental(hours). Prices: Regular Rs 15/km, Shared Rs 15/km split between riders (rounded down), Rental Rs 250/hour. Requirements: (1) a version where each ride computes its own price (polymorphism); (2) a separate Promo policy, outside the ride classes, that gives Rs 50 off rentals and 10% off regular rides, written as an exhaustive switch over a sealed interface.

Solution
sealed interface Ride permits Regular, Shared, Rental {
    int price();
}
record Regular(int km) implements Ride {
    public int price() { return 15 * km; }
}
record Shared(int km, int riders) implements Ride {
    public int price() { return 15 * km / riders; }
}
record Rental(int hours) implements Ride {
    public int price() { return 250 * hours; }
}
public class Main {
    static int discount(Ride r) {
        return switch (r) {
            case Regular g -> g.price() / 10;
            case Shared s -> 0;
            case Rental t -> 50;
        };
    }
    public static void main(String[] args) {
        Ride[] rides = { new Regular(10), new Shared(10, 3), new Rental(2) };
        for (Ride r : rides)
            System.out.println(r + ": Rs " + r.price() + " - Rs " + discount(r) + " = Rs " + (r.price() - discount(r)));
    }
}

Output:

Regular[km=10]: Rs 150 - Rs 15 = Rs 135
Shared[km=10, riders=3]: Rs 50 - Rs 0 = Rs 50
Rental[hours=2]: Rs 500 - Rs 50 = Rs 450

price() is polymorphic (each ride knows its own price); discount is an outside policy, and the compiler checks it covers every ride kind.

Practice

  1. What does this print?
class Animal { String sound() { return "..."; } }
class Dog extends Animal { @Override String sound() { return "Woof"; } }
public class Main {
    static String describe(Animal a) { return "animal says " + a.sound(); }
    static String describe(Dog d) { return "dog says " + d.sound(); }
    public static void main(String[] args) {
        Animal a = new Dog();
        System.out.println(describe(a));
    }
}
Solution

animal says Woof. The overload is chosen at compile time by the declared type (Animal), but sound() is overridden, so dynamic dispatch runs Dog.sound().

  1. Which of these can be overridden: (a) static int count(), (b) private void log(), (c) final int fee(), (d) int fee()?
Solution

Only (d). Static methods are hidden, not overridden; private methods aren't inherited; final methods can't be overridden.

  1. Rewrite with pattern matching: if (o instanceof String) { String s = (String) o; System.out.println(s.length()); }
Solution

if (o instanceof String s) System.out.println(s.length());

  1. A NotificationService has if (n.type == SMS) sendSms(n); else if (n.type == EMAIL) sendEmail(n); in five places. What refactoring applies, and what do you get?
Solution

Replace conditional with polymorphism: a Notification interface with send(), implemented by SmsNotification and EmailNotification; the five places call n.send(). A new channel is one new class.

Quick quiz

class A { String hi() { return "A"; } }
class B extends A {
    @Override String hi() { return "B"; }
}
A x = new B();
System.out.println(x.hi());
  • A
  • B
  • Compile error
  • ClassCastException
Answer

B. hi() is overridden, so dynamic dispatch runs the actual object's version. If hi were an overload taking A vs B as a parameter, the declared type would decide instead.

Interview questions

  1. What is polymorphism? The ability of one call or one reference type to work with objects of many types, each responding in its own way.
  2. Compile-time vs runtime polymorphism? Compile-time: method overloading, resolved by the compiler from declared argument types. Runtime: method overriding, resolved by the JVM from the actual object (dynamic dispatch).
  3. What is dynamic dispatch? Selecting an overridden method implementation at run time based on the receiving object's actual class.
  4. Which methods aren't virtual in Java? static, private and final methods (and constructors).
  5. Can overloading be based on return type alone? No; parameter lists must differ.
  6. Upcasting vs downcasting? Upcasting (subclass to superclass) is implicit and safe; downcasting needs an explicit cast and can throw ClassCastException, so check with instanceof.
  7. What is pattern matching for instanceof / switch? Java 16 lets x instanceof T t test and bind in one step; Java 21 lets switch match on types (case Car c ->) and checks exhaustiveness over sealed types.
  8. What is a covariant return type? An overriding method returning a subtype of the overridden method's return type, e.g. Car copy() overriding Vehicle copy().
  9. How do you remove a type-code switch? Replace conditional with polymorphism: move each branch into a subclass override, or use a sealed hierarchy with an exhaustive switch when the operation belongs outside the classes.

Glossary

Term Meaning, with an example
Polymorphism One call behaving differently depending on the object that receives it. v.fee(3)
Type code A string or number standing for a kind of object. "BIKE", "CAR"
switch Picks a branch by matching a value against cases. switch (v.type) { case "CAR": ... }
Runtime polymorphism The method to run is chosen while the program runs (overriding)
Method overriding A subclass redefining a superclass method with the same signature. Ev.fee
Declared type The type written for a variable. Vehicle in Vehicle v = new Ev(...)
Actual (runtime) type The class of the object created with new. Ev
Dynamic dispatch Choosing the override by the actual object at run time
Virtual method A method chosen by dynamic dispatch; all Java instance methods except static, private, final
Compile-time polymorphism The method is chosen by the compiler (overloading)
Method overloading Same name, different parameter lists. print(int), print(String, int)
Parameter list The number, types and order of a method's parameters
Ambiguous call A call two overloads fit equally; a compile error
double A number type with a decimal part. 45.5
Casting Treating a value as another type. (Car) v
Upcasting Treating a subclass object as its superclass type; automatic. Vehicle v = new Car(...)
Downcasting Treating a superclass reference as a subclass type; explicit. Car c = (Car) v
ClassCastException Run-time error when a downcast is wrong
instanceof Operator testing whether an object is an instance of a type. v instanceof Car
Pattern matching for instanceof v instanceof Car c: test and name in one step (Java 16)
Switch pattern matching switch (v) { case Car c -> ... }: matching on types (Java 21)
Exhaustive switch A switch handling every possible input; checked by the compiler for sealed types
Sealed interface An interface listing its only implementations with permits
Record A compact immutable data class. record Car(String plate, boolean ev)
Covariant return type An override returning a subtype of the original return type. Car copy()
Code smell A pattern in code that hints at a design problem. A repeated type switch
Refactoring Changing code's structure without changing its behaviour
Replace conditional with polymorphism Moving each branch of a type switch into a subclass override

Summary

  • Polymorphism: one call, many behaviours.
  • Runtime: overriding + dynamic dispatch; the actual object picks the method. All instance methods are virtual except static, private, final.
  • Compile-time: overloading; the compiler picks by declared types, so a Vehicle variable holding a Car gets the Vehicle overload.
  • Upcasting is automatic; downcasting is a promise; check with instanceof / pattern matching (Java 16).
  • Sealed types + switch pattern matching (Java 21) make the compiler check every kind.
  • Covariant returns let overrides return a narrower type.
  • Replace conditional with polymorphism turns type switches into one call.

Next episode: OOP 5: object relationships, coupling and cohesion.