What is Polymorphism?

Polymorphism is a fancy word that means "many shapes." In programming, it means that one thing (like a function or an object) can behave in different ways depending on the context.

Simple Example: Pets

Imagine you have different types of pets: a dog, a cat, and a bird. Each pet can make a sound, but the sound they make is different.

  1. Dog barks

  2. Cat meows

  3. Bird chirps

Using a Common Command

You can tell each pet to "make a sound," and they will each respond in their own way:

  • When you tell the dog to make a sound, it barks.

  • When you tell the cat to make a sound, it meows.

  • When you tell the bird to make a sound, it chirps.

So, the command "make a sound" is the same for all pets, but the result is different depending on which pet you are talking to.

In Programming

In programming, polymorphism allows you to write code that can work with different types of objects in a similar way.

Example in Code

Here's a simple example using a programming language:

  1. Define a common interface:
type Pet interface {
    MakeSound() string
}
  1. Create different types of pets that follow this interface:
type Dog struct {}
func (d Dog) MakeSound() string {
    return "Bark"
}

type Cat struct {}
func (c Cat) MakeSound() string {
    return "Meow"
}

type Bird struct {}
func (b Bird) MakeSound() string {
    return "Chirp"
}
  1. Use the interface to interact with any pet:
func main() {
    var pet Pet

    pet = Dog{}
    fmt.Println(pet.MakeSound()) // Outputs: Bark

    pet = Cat{}
    fmt.Println(pet.MakeSound()) // Outputs: Meow

    pet = Bird{}
    fmt.Println(pet.MakeSound()) // Outputs: Chirp
}

Why is this Useful?

  • Simplicity: You can use one common command or method to interact with different types of objects.

  • Flexibility: You can add new types of objects (new pets) without changing the code that uses them.

Polymorphism makes your code more flexible and easier to maintain by allowing you to use a single interface to work with different types of objects, each responding in their own way. It's like having one remote control that works with your TV, radio, and air conditioner—each device responds to the same commands but does its own thing.