On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. One Call, Many Results
  4. 2. Functions That Accept Any Child
  5. 3. Variable Type vs Real Type
  6. 4. Reaching a Child's Own Methods With is
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 044: Polymorphism

DayExtra Topics
Lecture044 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

"Polymorphism" means "many forms". One line of code, animal.sound(), can bark, meow or moo depending on which object it is given. It lets you write code once and use it for many different classes.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 042–043: inheritance and overriding.


Learning Objectives

  • Explain polymorphism in plain words
  • Store different child objects in one parent-typed list
  • Write a function that works for every child class
  • Know the difference between a variable's type and the object's real type
  • Use is to reach a child's own methods safely

1. One Call, Many Results

dart
class Animal {
  void sound() => print('...');
}

class Dog extends Animal {
  @override
  void sound() => print('Woof!');
}

class Cat extends Animal {
  @override
  void sound() => print('Meow!');
}

class Cow extends Animal {
  @override
  void sound() => print('Moo!');
}

void main() {
  List<Animal> farm = [Dog(), Cat(), Cow()];
  for (var animal in farm) {
    animal.sound();
  }
}

Output

code
Woof!
Meow!
Moo!

The loop only knows it has Animals. Each object still runs its own sound(). That is polymorphism.

2. Functions That Accept Any Child

A parameter of the parent type accepts every child:

dart
void makeItSpeak(Animal a) {
  a.sound();
}

makeItSpeak(Cat());   // Meow!

Add a Horse class tomorrow, and makeItSpeak works for it with no changes.

3. Variable Type vs Real Type

dart
Animal pet = Dog();
pet.sound();            // Woof!: the real object is a Dog
print(pet.runtimeType); // Dog
  • The variable's type (Animal) decides which methods you are allowed to call.
  • The object's real type (Dog) decides which version actually runs.

4. Reaching a Child's Own Methods With is

If Dog has a fetch() method that Animal doesn't, an Animal variable can't call it directly. Check with is first; inside the if, Dart treats it as a Dog:

dart
if (pet is Dog) {
  print('pet is a Dog');
  // pet.fetch();  // allowed here
}

Code Examples

Example 1: A Checkout With Many Payment Types

dart
class Payment {
  final double amount;
  Payment(this.amount);
  void pay() => print('Paying Rs $amount');
}

class CardPayment extends Payment {
  final String last4;
  CardPayment(super.amount, this.last4);
  @override
  void pay() => print('Charging Rs $amount to card ending $last4');
}

class CashPayment extends Payment {
  CashPayment(super.amount);
  @override
  void pay() => print('Collecting Rs $amount in cash');
}

class WalletPayment extends Payment {
  final String app;
  WalletPayment(super.amount, this.app);
  @override
  void pay() => print('Sending Rs $amount request to $app');
}

void checkout(List<Payment> payments) {
  var total = 0.0;
  for (var p in payments) {
    p.pay();
    total += p.amount;
  }
  print('Total paid: Rs $total');
}

void main() {
  checkout([
    CardPayment(1200, '4421'),
    CashPayment(300),
    WalletPayment(850, 'JazzCash'),
  ]);
}

Output

code
Charging Rs 1200.0 to card ending 4421
Collecting Rs 300.0 in cash
Sending Rs 850.0 request to JazzCash
Total paid: Rs 2350.0

checkout never asks "which kind of payment is this?". Each payment knows how to pay itself.


Common Beginner Mistakes

1. Calling a child-only method through a parent variable

dart
Animal pet = Dog();
pet.fetch();
code
Error: The method 'fetch' isn't defined for the type 'Animal'.

Check if (pet is Dog) first, or declare the variable as Dog.

2. Long if/else chains on type: if (p is CardPayment) ... else if (p is CashPayment) ... is a sign you should override a method instead and just call p.pay().

3. Forgetting to override: if a child doesn't override sound(), it silently uses the parent's version (...). Lecture 045 shows how abstract methods force every child to provide one.


Practice Questions

  1. What does "polymorphism" mean in one sentence?
  2. Animal a = Cat(); a.sound();: whose sound() runs?
  3. What does print(a.runtimeType); print for the same a?
  4. Why can a List<Animal> hold a Dog and a Cow?
  5. You add a Goat class that overrides sound(). What must change in the for loop from Section 1?

Practice Answers

  1. The same method call behaves differently depending on the object's real class.
  2. Cat's: it prints Meow!.
  3. Cat
  4. Because a dog and a cow are both animals (they extend Animal).
  5. Nothing. Just add Goat() to the list.

Key Takeaways

  • Polymorphism: one call (animal.sound()), many behaviours.
  • A parent-typed variable, list or parameter can hold any child object.
  • The variable's type limits what you can call; the real object decides what runs.
  • Use is to safely use a child's own methods.
  • Prefer overriding over long if (x is ...) chains.