Start learning free

LESSON 637 OF 671 · OBJECT-ORIENTED PROGRAMMING

Polymorphism in Go

Lesson

TL ; DR:

Polymorphism is when a single piece of code (like animal.speak()) does different things depending on which concrete type the value actually holds. You write the call once, and the right method runs automatically.


animals := []Animal{Dog{}, Cat{}}
for _, a := range 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 have a speak() method, they both satisfy the Animal interface (Go interfaces are satisfied implicitly, with no implements keyword), and 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:

func roll(animals []Animal) {
    for _, a := range animals {
        a.speak()
    }
}

This function works for any current or future kind of animal. Add a Cow type with a speak() method 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 variable is typed as Animal. The value it actually holds 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

  • Go — calling a method through an interface value always runs the method of the concrete type stored in it. No keyword is needed.
  • C# / C++ — the parent method must be virtual (and the override marked override) for runtime dispatch. Otherwise you get static dispatch and the wrong version runs.
  • Java / JS / Python — methods are virtual by default. Just override and it works.

Your task

Animal, Dog, and Cat are already defined, each type with its own speak() method. 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
Meow
STEP 1 OF 3
    Ctrl + Enter to check