Polymorphism (Many Forms) allows objects to decide effectively which method implementation to run at runtime. It lets you write generic code that works with many object types.
1. Defining Polymorphism
It sounds complex, but it simply means: Treating a specific object (like a Dog) as its generic parent (Animal).
The Zoo Example
1class Animal {2 void makeSound() => print('Some sound...');3}4 5class Dog extends Animal {6 @override7 void makeSound() => print('Woof');8}9 10class Cat extends Animal {11 @override12 void makeSound() => print('Meow');13}14 15void main() {16 Animal myPet = Dog(); // Treated as Animal, but is actually a Dog17 myPet.makeSound(); // Prints "Woof" (Runtime knows it's a dog)18}HintEven though the variable type is Animal, Dart runs the Dog version of the method.
2. Why is this useful?
It allows you to use Arrays/Lists of mixed types (as long as they share a parent).
Mixed List
1void main() {2 // A list of Animals (can hold Dogs, Cats, etc.)3 List<Animal> zoo = [4 Dog(),5 Cat(),6 Dog(),7 Animal()8 ];9 10 for (var animal in zoo) {11 animal.makeSound(); 12 // Just works! The loop doesn't care exactly what it is.13 }14}HintWithout polymorphism, you would need separate lists: List<Dog>, List<Cat>, etc.
3. The @override Annotation
While optional, ALWAYS use @override when you intend to replace a parent method. It helps the compiler catch typos.
Safety First
1class Robot {2 void powerOn() {}3}4 5class Android extends Robot {6 // ✅ Good: Compiler checks if 'powerOn' exists in parent7 @override8 void powerOn() => print('Android booting...');9 10 // ❌ Bad: If you typo 'powerOn' to 'pwerOn' without @override,11 // Dart thinks you made a new method instead of replacing the old one.12}HintAnnotations help your tools help you.
Loot collected
Key takeaways- Polymorphism means treating subclasses as their superclass.
- It enables flexibility: A method
feed(Animal a)can accept a Dog, Cat, or Lion. - Runtime dispatch ensures the correct method (Dogs bark, Cats meow) is called.
- Always use
@override.
Side quests
Practice exercises
Exercise 1: Payment System
Create a parent Payment class and children Cash, Credit that override pay().
Reveal solutionHide solution
1class Payment { pay() {} } class Cash extends Payment { @override pay() => print('Cash'); }Exercise 2: Loop Payments
Create a list of Payments and loop through calling pay().
Reveal solutionHide solution
1List<Payment> list = [Cash(), Credit()]; list.forEach((p) => p.pay());