TL ; DR:
Polymorphism is when a single piece of code (like animal.speak()) does different things depending on which subclass the object actually is. You write the call once, and the right override runs automatically.
Animal[] animals = { new Dog(), new Cat() }
for (Animal a : animals) {
a.speak() // dispatches to Dog.speak then Cat.speak
}
Full lesson:
Polymorphism (Greek for "many forms") is what makes inheritance and interfaces actually useful at scale. Once Dog and Cat both inherit from Animal and override speak(), you can stop caring which one you're holding. Any code that takes an Animal and calls speak() works for both.
Why it matters
Imagine you're writing a function that prints what every animal in a zoo says:
void Roll(Animal[] animals) {
foreach (var a in animals) a.Speak()
}
This function works for any current or future kind of animal. Add a Cow subclass tomorrow — this loop runs Cow.Speak() automatically, no edits needed. That's the win: code that works today and keeps working as the type hierarchy grows.
Static type vs dynamic type
The reference is typed as Animal. The object it actually points to is a Dog, or a Cat, etc. Polymorphism is the language dispatching the method call based on the dynamic type (what it is at runtime) rather than the static type (what the variable was declared as).
Notes by language
- C# / C++ — the parent method must be
virtual(and the override markedoverride) for runtime dispatch. Otherwise you get static dispatch and the wrong version runs. - Scala / JS / Python — methods are virtual by default. Just override and it works.
Your task
Animal, Dog, and Cat are already defined, with the right overrides. Inside MainFunction, build a collection containing one Dog and one Cat (typed as Animal), then loop through it calling speak() on each.
Expected output:
Woof
MeowFree plan: 30 tutor messages. Premium is unlimited.