1 min read

Polymorphism

Background

Polymorphism is a programming concept where different classes share the same methods, but have different outcomes.

Example:

You have an Animal base class, and a Dog and a Cat class that inherit from it. All animals make sounds, but different kinds make different sounds. With polymorphism, we can make animals make sounds without knowing the species of the animal.

What we avoid w/ polymorphism

Because we don't need to write conditional statements to type-check each animal, the code becomes easier to read and write and tightly couples dog/cat-specific code.

if type(animal) == Dog:
	print('BARK BARK BARK')
elif type(animal) == Cat:
	print('meow')
elif type(animal) == Crow:
	print('CAW CAW')
...

The more species of animals there are, the more if statements we'd write, and the more complex and ugly the code gets. Polymorphism lets us abstract away the details of making animal noises to the classes.