SyntaxPilot
Courses/Java/Lesson 19
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 19 of 51

Polymorphism: compile time vs runtime

queued

These are the notes for Java episode 19. Episode 18 ended with a question: one array of Person holds a plain person and a student; when we call introduce() on each, which version runs? Today's answer is polymorphism. You will see why type strings and if/else chains break, make one loop drive many behaviours with overriding, understand upcasting with the TV-remote picture (reference type vs object type), read the real "cannot find symbol ... of type Person" error, use instanceof before a downcast (or get a ClassCastException), revisit overloading as compile-time polymorphism, and solve the classic overload-vs-override trap. Every example was run with javac 21.

The problem: one bell, everyone does their own thing

Nine a.m., the school bell rings. Students go to class, teachers go to teach, the guard opens the gate. Nobody gives each kind of person a separate instruction: one signal, and each knows its own job.

The obvious attempt: a type string and an if/else chain

class Person {
    String name;
    String type;
    Person(String name, String type) {
        this.name = name;
        this.type = type;
    }
}

public class Main {
    static void bell(Person p) {
        if (p.type.equals("student")) {
            System.out.println(p.name + " goes to class");
        } else if (p.type.equals("teacher")) {
            System.out.println(p.name + " goes to teach");
        }
    }

    public static void main(String[] args) {
        Person[] people = {
            new Person("Aarav", "student"),
            new Person("Meena", "teacher"),
            new Person("Mr. Rao", "guard")
        };
        for (Person p : people) {
            bell(p);
        }
    }
}
Aarav goes to class
Meena goes to teach

The guard silently does nothing: no error, no output. Nobody updated the chain.

Why it went wrong

  • The caller decides what each kind of person does, and that knowledge is spread over every chain (bell, fees, idCard...).
  • Every new kind means hunting down and editing every chain.
  • The compiler can't help: a typo in "teacher" or a missed branch is a silent bug.
  • The fix flips it around: don't ask "what type are you?". Ring the bell and let each object decide, using overriding from episode 18.

Runtime polymorphism: one loop, many behaviours

class Person {
    String name;
    Person(String n) { name = n; }
    void onBell() {
        System.out.println(name + " waits");
    }
}

class Student extends Person {
    Student(String n) { super(n); }
    @Override void onBell() {
        System.out.println(name + " goes to class");
    }
}

class Teacher extends Person {
    Teacher(String n) { super(n); }
    @Override void onBell() {
        System.out.println(name + " goes to teach");
    }
}

class Guard extends Person {
    Guard(String n) { super(n); }
    @Override void onBell() {
        System.out.println(name + " opens the gate");
    }
}

public class Main {
    public static void main(String[] args) {
        Person[] people = { new Student("Aarav"),
            new Teacher("Meena"), new Guard("Mr. Rao") };
        for (Person p : people) {
            p.onBell();
        }
    }
}
Aarav goes to class
Meena goes to teach
Mr. Rao opens the gate
  • The array's type is Person, but it holds a Student, a Teacher and a Guard.
  • The same line, p.onBell(), does three different things: each object runs its own override.
  • Adding a Principal means writing one new class. The loop never changes.

Polymorphism (Greek: poly = many, morph = form) means one name, many forms: the same call behaves differently depending on the object.

The remote and the TV: reference type vs object type

A TV remote In Java
The remote: a basic one with power and volume The reference type: Person p
The TV it's pointed at decides what happens The object type: new Student(...)
No Netflix button, even if the TV has Netflix p.getRoll(): compile error
  • Upcasting: storing a child object in a parent-type variable, Person p = new Student("Aarav", 12);. Always allowed (a student is a person), no cast needed.
  • The reference type decides what you may call, at compile time. The compiler only looks at the remote.
  • The object type decides which version runs, at runtime. Java looks at the real object while the program runs and calls its override. This is runtime polymorphism, also called dynamic method dispatch.
class Person {
    String name;
    Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    int roll;
    Student(String name, int roll) {
        super(name);
        this.roll = roll;
    }
    int getRoll() {
        return roll;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Student("Aarav", 12);
        System.out.println(p.name);
        System.out.println(p.getRoll());
    }
}
Main.java:23: error: cannot find symbol
        System.out.println(p.getRoll());
                            ^
  symbol:   method getRoll()
  location: variable p of type Person
1 error

The object really is a Student, but the compiler checks the reference type Person, and Person has no getRoll().

instanceof and downcasting

To use child-only methods, first ask the object what it really is. Downcasting converts a parent reference back to a child type.

class Person {
    String name;
    Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    int roll;
    Student(String name, int roll) {
        super(name);
        this.roll = roll;
    }
}

class Teacher extends Person {
    Teacher(String name) {
        super(name);
    }
}

public class Main {
    public static void main(String[] args) {
        Person[] people = { new Student("Aarav", 12), new Teacher("Meena") };
        for (Person p : people) {
            if (p instanceof Student s) {
                System.out.println(s.name + " has roll " + s.roll);
            } else {
                System.out.println(p.name + " has no roll number");
            }
        }
        Student wrong = (Student) people[1];
    }
}
Aarav has roll 12
Meena has no roll number
Exception in thread "main" java.lang.ClassCastException: class Teacher cannot be cast to class Student (Teacher and Student are in unnamed module of loader 'app')
    at Main.main(Main.java:32)
  • p instanceof Student s is true only if the object really is a Student (or a subclass); then s is a Student variable you can use inside the if (pattern matching for instanceof, Java 16+). The older form is if (p instanceof Student) { Student s = (Student) p; ... }.
  • (Student) people[1] compiles (a Person might be a Student), but at runtime the object is a Teacher, so Java throws a ClassCastException.
  • Casting between unrelated types doesn't even compile, e.g. (String) p gives error: incompatible types: Person cannot be converted to String.
  • Code full of instanceof checks is the if/else chain coming back. Prefer an overridden method.

Compile-time polymorphism: overloading

At a chai stall, "one chai" and "one chai, less sugar" use the same word, but the details you give pick the version. In Java, the same method name with different parameters is method overloading (episode 11). The compiler picks the version from the argument types, so this is compile-time (or static) polymorphism.

public class Main {
    static int area(int side) {
        return side * side;
    }
    static int area(int length, int width) {
        return length * width;
    }
    static double area(double radius) {
        return 3.14 * radius * radius;
    }

    public static void main(String[] args) {
        System.out.println(area(5));
        System.out.println(area(4, 6));
        System.out.println(area(2.0));
    }
}
25
24
12.56

System.out.println itself is overloaded: println(int), println(String), println(double)...

Two traps:

static int area(int side) { ... }
static double area(int side) { ... }
Main.java:5: error: method area(int) is already defined in class Main
    static double area(int side) {
                  ^
1 error

The return type alone doesn't make a different overload.

static void pay(int rupees, double tip) { ... }
static void pay(double rupees, int tip) { ... }
// pay(10, 20);
Main.java:10: error: reference to pay is ambiguous
        pay(10, 20);
        ^
  both method pay(int,double) in Main and method pay(double,int) in Main match
1 error

Both versions match equally well, so the compiler refuses to guess.

The trap: overloading is compile time, overriding is runtime

class Person {
    void introduce() {
        System.out.println("introduce: Person");
    }
}

class Student extends Person {
    @Override
    void introduce() {
        System.out.println("introduce: Student");
    }
}

public class Main {
    static void describe(Person p) {
        System.out.println("describe: Person");
    }
    static void describe(Student s) {
        System.out.println("describe: Student");
    }

    public static void main(String[] args) {
        Person p = new Student();
        describe(p);
        p.introduce();
    }
}
describe: Person
introduce: Student
  • describe(p) is an overload choice, made at compile time from the reference type Person.
  • p.introduce() is an override choice, made at runtime from the real object, a Student.
Overloading Overriding
Also called Compile-time / static polymorphism Runtime / dynamic polymorphism
Where Usually the same class Parent and child classes
Parameters Different Same
Chosen by The compiler, from argument (reference) types The JVM, from the real object
Return type Can differ (but can't be the only difference) Same (or a subtype)
static / private / final methods Can be overloaded Can't be overridden

Also note: fields aren't polymorphic. If a parent and child both declare a field name, p.name uses the reference type's field. Only methods are dispatched at runtime.

What you just invented

Problem Fix
A type string and if/else chains everywhere Each child overrides the method; call it through a parent reference
One collection of many kinds Person[] people, upcasting
Need a child-only method instanceof pattern, then use the child variable
One action, different inputs Overloading, picked by the compiler

That's polymorphism: new kinds of objects plug in without touching the old code.

The next problem: shapes. Circle and Square override area(), but what does the parent Shape return? A plain shape has no area, so we write a fake return 0;. And a Triangle that forgets to override area() silently has area 0, with no error. Episode 20: abstract classes.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
Person p = new Student(...); p.getRoll(); error: cannot find symbol / location: variable p of type Person The reference type decides what you may call if (p instanceof Student s) s.getRoll();
(Student) people[1] when it's a Teacher java.lang.ClassCastException: class Teacher cannot be cast to class Student The real object isn't a Student Check with instanceof first
Two methods differing only in return type error: method area(int) is already defined in class Main Return type isn't part of the overload choice Change the parameters
pay(int, double) + pay(double, int), pay(10, 20) error: reference to pay is ambiguous Both match equally pay(10, 20.0), or rename
Type strings + if/else for behaviour no error, a branch is silently missed The caller decides for every kind Override in each subclass
Expecting overloads to follow the real object no error, the "wrong" overload runs Overloads are chosen at compile time Use overriding for per-object behaviour

Mini project: a payment counter

class Payment {
    int amount;
    Payment(int amount) { this.amount = amount; }
    void pay() {
        System.out.println("Paid " + amount);
    }
}

class Upi extends Payment {
    String id;
    Upi(int amount, String id) { super(amount); this.id = id; }
    @Override void pay() {
        System.out.println("UPI " + id + ": Rs " + amount + " sent");
    }
}

class Card extends Payment {
    Card(int amount) { super(amount); }
    @Override void pay() {
        int fee = amount / 100;
        System.out.println("Card: Rs " + amount + " + Rs " + fee + " fee");
    }
}

class Cash extends Payment {
    int given;
    Cash(int amount, int given) { super(amount); this.given = given; }
    @Override void pay() {
        System.out.println("Cash: change Rs " + (given - amount));
    }
}

public class Main {
    static int total(Payment[] all) {
        int sum = 0;
        for (Payment p : all) {
            sum += p.amount;
        }
        return sum;
    }

    public static void main(String[] args) {
        Payment[] today = { new Upi(120, "aarav@upi"), new Card(2500), new Cash(80, 100) };
        for (Payment p : today) {
            p.pay();
        }
        System.out.println("Total: Rs " + total(today));
    }
}
UPI aarav@upi: Rs 120 sent
Card: Rs 2500 + Rs 25 fee
Cash: change Rs 20
Total: Rs 2700

Adding NetBanking later means one new class; the loop and total don't change.

Practice

  1. Add a Principal class that prints "<name> rings the bell" to the bell program, without editing Main's loop.
  2. Predict the output:
class A {
    void show() {
        System.out.println("A.show");
    }
}

class B extends A {
    @Override
    void show() {
        System.out.println("B.show");
    }
    void extra() {
        System.out.println("B.extra");
    }
}

public class Main {
    static void call(A a) {
        System.out.println("call(A)");
        a.show();
    }
    static void call(B b) {
        System.out.println("call(B)");
        b.show();
    }

    public static void main(String[] args) {
        A x = new B();
        call(x);
        call(new B());
        if (x instanceof B b) {
            b.extra();
        }
    }
}
  1. Write three overloads print(int), print(String) and print(int[]) that print int: ..., text: ... and array of N.
Solutions

1. Add the class and put a new Principal("Dr. Rao") in the array; nothing else changes:

class Principal extends Person {
    Principal(String n) { super(n); }
    @Override void onBell() {
        System.out.println(name + " rings the bell");
    }
}

2.

call(A)
B.show
call(B)
B.show
B.extra

call(x) picks call(A) at compile time (x is an A reference), but a.show() runs B's override at runtime.

3.

public class Main {
    static void print(int n) {
        System.out.println("int: " + n);
    }
    static void print(String s) {
        System.out.println("text: " + s);
    }
    static void print(int[] arr) {
        System.out.println("array of " + arr.length);
    }

    public static void main(String[] args) {
        print(7);
        print("chai");
        print(new int[] {1, 2, 3});
    }
}
int: 7
text: chai
array of 3

Quick quiz

class Animal {
    void sound() { System.out.print("... "); }
}
class Dog extends Animal {
    @Override
    void sound() { System.out.print("Woof "); }
}
class Cat extends Animal {
    @Override
    void sound() { System.out.print("Meow "); }
}
class Cow extends Animal { }
// in main:
Animal[] farm = { new Dog(), new Cat(), new Cow() };
for (Animal a : farm) a.sound();

A) ... ... ... B) Woof Meow ... C) Woof Meow Moo D) Compile error: Cow has no sound()

Answer

B. Each call runs the real object's version: Dog → Woof, Cat → Meow. Cow doesn't override sound(), so it inherits Animal's ....

Interview questions

  1. What is polymorphism? The ability of one call or name to take many forms: the same method call behaves differently depending on the object (overriding) or the arguments (overloading).
  2. Runtime vs compile-time polymorphism? Runtime: overriding, chosen by the JVM from the actual object (dynamic method dispatch). Compile-time: overloading, chosen by the compiler from the argument types.
  3. What is upcasting? Downcasting? Upcasting: a child object in a parent reference (implicit, always safe). Downcasting: a parent reference cast to a child type (explicit, checked at runtime; can throw ClassCastException).
  4. What is dynamic method dispatch? The mechanism by which the JVM decides at runtime which overridden method to call, based on the object's actual class.
  5. Can static methods be overridden? No. A static method with the same signature in the child hides the parent's; the call is resolved at compile time from the reference type.
  6. Are fields polymorphic? No, field access uses the reference type.
  7. Why is a long instanceof chain a design smell? It moves behaviour back into the caller; adding a type means editing the chain. Overriding keeps behaviour with the object (open for extension, closed for modification).
  8. Can overloaded methods differ only by return type? No: method ... is already defined.

Glossary

Term Meaning Example
Polymorphism One name or call, many forms p.onBell() on different people
Runtime polymorphism The overridden method is chosen while the program runs, from the real object Guard's onBell()
Dynamic method dispatch The JVM's runtime choice of which override to call
Compile-time (static) polymorphism The compiler chooses among overloads from the argument types area(5) vs area(2.0)
Reference type The declared type of a variable; decides what you may call Person in Person p
Object type (runtime type) The class of the actual object Student in new Student()
Upcasting Storing a child object in a parent-type variable Person p = new Student(...)
Downcasting Converting a parent reference to a child type (Student) p
instanceof Checks whether an object is of a given type p instanceof Student s
Pattern matching for instanceof instanceof that also declares a typed variable (Java 16+) if (p instanceof Student s)
ClassCastException Runtime error when a cast doesn't match the real object Teacher cast to Student
Method overloading Same name, different parameters area(int), area(int, int)
Method overriding A child redefines a parent method with the same signature @Override void onBell()
Ambiguous call More than one overload matches equally well pay(10, 20)

Summary

  • Type strings and if/else chains break silently with every new kind.
  • Override the method in each child, and call it through a parent reference: one call, many behaviours.
  • Reference type = what you may call (compile time). Object type = which override runs (runtime).
  • Upcasting is automatic; downcasting needs a check: instanceof, or risk a ClassCastException.
  • Overloading = same name, different parameters, chosen by the compiler.
  • Overload choice uses the reference type; override choice uses the real object.
  • Next: a Shape whose area() can only return a fake 0. Episode 20: abstract classes.