Thuta Learning
Java
AdvancedProgrammingBeginner

Polymorphism

JavaLesson 2030 min

What you'll walk away with

  • Separate a variable's declared (compile-time) type from its runtime class and predict the output
  • Explain how overridden instance methods are chosen at runtime by dynamic dispatch
  • Recognise that overload selection, fields and static methods are not polymorphic
  • Downcast safely with an instanceof pattern and switch over a sealed type

Explain it simply

Polymorphism in plain language

Polymorphism means "many forms". Your code knows only a parent type, Animal, and calls makeSound(), yet the code that actually runs depends on the object's real class: a Dog barks and a Cat meows. One calling line, different results depending on the object.

Picture a TV remote. Pressing the power button is the same action every time, but what happens inside depends on which brand of TV it is pointed at. You only need to know the "power" command; each TV decides how to carry it out.

Problem → Why → Solution

The problem: an if-else chain that grows with every new type

Before learning polymorphism, developers often inspect an object's class and branch by hand. The method below works for two animals, but the day someone adds Bird and forgets to edit it, birds print "Unknown animal". Chains like this tend to be scattered across a codebase, so one new type means editing a dozen places.

SoundBoard.java
static void playSound(Animal animal) {
  if (animal instanceof Dog) {
    System.out.println("Woof!");
  } else if (animal instanceof Cat) {
    System.out.println("Meow!");
  } else {
    System.out.println("Unknown animal");   // every new Bird lands here
  }
}

Put the behaviour inside the object

The problem is that knowledge about how each animal sounds lives outside the objects. Polymorphism moves it back inside each class: Dog writes its own makeSound(), and calling code just says animal.makeSound(). Adding a Bird means writing one new class, with no existing line to edit.

Core concept: declared type versus runtime class

The line Animal pet = new Dog(); involves two types. Animal is the variable's declared type (its compile-time type), and Dog is the runtime class of the object on the heap. Because a Dog is an Animal, this assignment, called an upcast, needs no cast. Passing a Dog to a method whose parameter is Animal, or storing Dogs and Cats together in a List<Animal>, are upcasts too. All of polymorphism rests on who uses which of these two types, and for what.

The compiler looks only at the declared type. pet.makeSound() compiles because Animal has makeSound(), but pet.fetch() is a compile error since Animal has no fetch(), even though the object really is a Dog. When the program runs, the JVM looks at the runtime class and picks the overriding version, which is called dynamic dispatch or late binding. That is why pet.makeSound() runs Dog's version.

text
Who decides what
----------------
Animal pet = new Dog();
  |               |
  |               +--> runtime class: Dog  (JVM, while running)
  +--> declared type: Animal               (compiler, before running)

pet.makeSound()
  compiler: does Animal have makeSound()?   yes -> compiles
  JVM:      which class is the object?      Dog -> runs Dog.makeSound()

pet.fetch()
  compiler: does Animal have fetch()?       no  -> compile error

Dynamic dispatch applies only to overridden instance methods. Fields, static methods and private methods are resolved from the declared type. Choosing between overloads (same name, different parameters) is also done by the compiler, at compile time, from the declared types of the arguments. When you need a subclass-only method, check first with an instanceof pattern, if (pet instanceof Dog dog); a blind (Dog) pet cast throws ClassCastException when the object turns out to be a Cat.

In a deeper hierarchy the JVM starts at the runtime class and walks upwards, running the first override it finds. If Puppy extends Dog and does not override makeSound(), Dog's version runs. The real payoff is that a method accepting Animal works with classes that do not exist yet: a Parrot class written next month is handled by existing code without touching it.

The compiler permits, the object chooses
  1. Declared type limits what you may call
  2. Compiler has already picked the overload
  3. JVM checks the object's runtime class
  4. The closest override runs

Fields and static methods skip steps 3 and 4; they are resolved from the declared type alone.

General pattern

java
Parent ref = new Child();      // upcast: no cast needed
ref.overriddenMethod();        // runs Child's version

for (Parent item : listOfParents) {
  item.overriddenMethod();     // each object picks its own version
}

if (ref instanceof Child child) {   // safe downcast
  child.childOnlyMethod();
}

Store child objects in parent-typed variables and call overridden methods; downcast with an instanceof pattern only when you truly need a child-only method.

Worked example: one Animal reference, many sounds

Dog and Cat override Animal's makeSound(). main declares its variables as Animal and loops over a List<Animal>, yet each object runs its own version. At the end, an instanceof pattern reaches fetch(), which only Dog has.

Main.java
import java.util.List;

public class Main {
  public static void main(String[] args) {
    Animal animal1 = new Dog();
    Animal animal2 = new Cat();
    animal1.makeSound();
    animal2.makeSound();

    List<Animal> shelter = List.of(new Cat(), new Animal(), new Dog());
    for (Animal animal : shelter) {
      animal.makeSound();
    }

    // animal1.fetch();   // compile error: Animal has no fetch()
    if (animal1 instanceof Dog dog) {
      dog.fetch();
    }
  }
}

class Animal {
  public void makeSound() {
    System.out.println("The animal makes a sound");
  }
}

class Dog extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Dog says: Woof!");
  }

  public void fetch() {
    System.out.println("Dog fetches the ball");
  }
}

class Cat extends Animal {
  @Override
  public void makeSound() {
    System.out.println("Cat says: Meow!");
  }
}

Code breakdown

  1. UpcastAnimal animal1 = new Dog();

    The declared type is Animal and the runtime class is Dog. A Dog is an Animal, so no cast is needed.

  2. Override@Override

    Dog and Cat rewrite makeSound() with the same signature, and @Override asks the compiler to confirm it really is an override.

  3. One loop, three behavioursanimal.makeSound();

    This single line runs three different pieces of code for the Cat, the plain Animal and the Dog. The plain Animal, which overrides nothing, runs the parent version.

  4. Safe downcastif (animal1 instanceof Dog dog) {

    Writing animal1.fetch() directly is a compile error, because Animal has no fetch(). The instanceof pattern checks the object and binds dog only when it really is a Dog.

You should see
Dog says: Woof!
Cat says: Meow!
Cat says: Meow!
The animal makes a sound
Dog says: Woof!
Dog fetches the ball
How animal.makeSound() is resolved
  1. Compile time: check that Animal declares makeSound()
  2. Runtime: find the class of the object animal points to
  3. Look for an override in that class
  4. If there is none, walk up to the parent

Dog or Cat

Runs the subclass override

Plain Animal

Runs Animal.makeSound()

Overloads are chosen at compile time, overrides at runtime

The program below has two static greet methods (overloads), while speak() is overridden by Dog. Variable a is declared as Animal, so the compiler picks greet(Animal); the fact that the object is a Dog does not matter. a.speak() is chosen at runtime, so Dog's version runs.

Dispatch.java
public class Dispatch {
  static void greet(Animal a) { System.out.println("greet(Animal)"); }
  static void greet(Dog d) { System.out.println("greet(Dog)"); }

  public static void main(String[] args) {
    Animal a = new Dog();
    greet(a);                 // overload: picked from the declared type
    a.speak();                // override: picked from the runtime class
    greet(new Dog());         // declared type Dog -> greet(Dog)
  }
}

class Animal {
  void speak() { System.out.println("..."); }
}

class Dog extends Animal {
  @Override
  void speak() { System.out.println("Woof"); }
}

This program prints greet(Animal), then Woof, then greet(Dog).

Sealed types and pattern matching for switch (Java 21)

Overriding is best when the behaviour belongs inside each class. Sometimes, though, you want an operation such as drawing or JSON conversion kept outside the classes. A sealed class (Java 17) closes the list of subclasses, and pattern matching for switch (Java 21) lets you handle each type in its own case. Because the list is closed, the compiler checks that every case is covered, so no default branch is needed.

Shapes.java
import java.util.List;

public class Shapes {
  public static void main(String[] args) {
    for (Shape shape : List.of(new Circle(1.5), new Square(2.0))) {
      System.out.println(describe(shape));
    }
  }

  static String describe(Shape shape) {
    return switch (shape) {
      case Circle c -> "circle, radius " + c.radius;
      case Square s -> "square, side " + s.side;
    };
  }
}

sealed abstract class Shape permits Circle, Square {}

final class Circle extends Shape {
  final double radius;
  Circle(double radius) { this.radius = radius; }
}

final class Square extends Shape {
  final double side;
  Square(double side) { this.side = side; }
}

Why abstract matters here

If Shape were only sealed and not abstract, a plain new Shape() could exist, and the compiler rejects the switch with "the switch expression does not cover all possible input values". When you add a subclass you must update permits, and every such switch then fails to compile until you handle it.

In real projects

Polymorphism in real projects

Business applications are full of the "same action, different implementation" pattern. Checkout code calls payment.charge(amount), and the runtime object decides whether that means a card, a bank transfer or a mobile wallet. A report export calls exporter.write(rows) once and works with CSV, PDF and Excel exporters alike.

  • In the JDK, System.out.println(object) calls object.toString(). Override toString() in your class and println, string concatenation and log messages all use your version.
  • In the collections framework you write List<String> names = new ArrayList<>(); and switching to LinkedList later means editing only the right-hand side, because the rest of the code knows only List.
  • In tests you can swap a class that really sends email for a fake subclass that just records each message in a list, then assert on what was sent.

Common mistakes

Common mistakes with polymorphism

Overloading when you meant to override

Writing public boolean equals(Dog other) in Dog does not override Object's equals(Object); it adds a new overload. Code such as List.contains() calls equals(Object), so your method is never reached. Adding @Override makes the compiler catch this immediately.

Downcasting without checking

Animal a = new Cat(); Dog d = (Dog) a; compiles, then crashes at runtime with ClassCastException. When a downcast is needed, guard it with if (a instanceof Dog d). If you find yourself downcasting often, that is a sign the method belongs on the parent type.

Expecting static methods and fields to be polymorphic

If Parent and Child both declare static void info(), then Parent p = new Child(); p.info(); runs Parent's version, because static methods are hidden, not overridden. Fields with the same name behave the same way. Write behaviour that should vary at runtime as an instance method.

Best practices

Best practices

  • Declare variables and parameters with the most general type you need, such as List or Animal.
  • Before writing an instanceof chain, ask whether the behaviour can move into an overridden method.
  • Use a sealed type with a pattern switch when the subclass list is closed and the operation lives outside the classes.
  • Put @Override on every overriding method.

Mini challenge

Mini challenge: ticket pricing

Build a Ticket class with two subclasses, ChildTicket and SeniorTicket, for an exhibition. A Ticket costs 10.00, a ChildTicket 5.00, and a SeniorTicket 70% of the normal price. Loop over a List<Ticket> and print each ticket's price and the total.

  • Both subclasses override price() with @Override
  • SeniorTicket reuses super.price() instead of repeating 10.00
  • The loop calls ticket.price() only, with no instanceof
  • Print each class name with getClass().getSimpleName()
Tickets.java
import java.util.List;

public class Tickets {
  public static void main(String[] args) {
    List<Ticket> basket = List.of(new Ticket(), new ChildTicket(), new SeniorTicket());
    // TODO: loop, print "<ClassName>: <price with 2 decimals>" and add to a total
    // TODO: print "Total: <total with 2 decimals>"
  }
}

class Ticket {
  double price() {
    // TODO
  }
}

// TODO: ChildTicket overrides price() -> 5.00
// TODO: SeniorTicket overrides price() -> 70% of super.price()

Expected: Three lines, Ticket: 10.00, ChildTicket: 5.00 and SeniorTicket: 7.00, followed by Total: 22.00.

Show hint

printf("%s: %.2f%n", name, price) handles both formats. The loop variable is typed Ticket, but every price() call runs the object's own version, so you never need instanceof.

Show solution
Tickets.java
import java.util.List;

public class Tickets {
  public static void main(String[] args) {
    List<Ticket> basket = List.of(new Ticket(), new ChildTicket(), new SeniorTicket());
    double total = 0;
    for (Ticket ticket : basket) {
      double price = ticket.price();
      System.out.printf("%s: %.2f%n", ticket.getClass().getSimpleName(), price);
      total += price;
    }
    System.out.printf("Total: %.2f%n", total);
  }
}

class Ticket {
  double price() {
    return 10.00;
  }
}

class ChildTicket extends Ticket {
  @Override
  double price() {
    return 5.00;
  }
}

class SeniorTicket extends Ticket {
  @Override
  double price() {
    return super.price() * 0.7;
  }
}

Quick quiz 1 / 3

Given class A { String name = "A"; } and class B extends A { String name = "B"; }, what does A x = new B(); System.out.println(x.name); print?

Quick quiz 2 / 3

What happens with Animal a = new Cat(); Dog d = (Dog) a;?

Quick quiz 3 / 3

There are two overloads, static void show(Animal a) and static void show(Dog d). Which one does Animal pet = new Dog(); show(pet); call?

What to remember

  • Every variable has two types: its declared type and the runtime class of the object it holds.
  • The declared type limits which methods you may call; the runtime class decides which override runs.
  • Overload selection, fields and static methods are settled at compile time from the declared type.
  • Guard downcasts with an instanceof pattern, and use a sealed type with a pattern switch when the subclass list is closed.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Polymorphism | Thuta Learning