Changing Roles

Through the day, people treat Chloe as a student, a singer or an athlete. Each sees only the role it needs. Polymorphism shifts focus in the same way.

Apprentice · C# · OOP · Updated

After this lesson you can

  • Explain how treating an object as one of its forms limits what you can ask it to do

Key takeaways

  • Seeing an object as one of its forms means asking only what that form can do. The object itself doesn't change.
  • Code that holds an Archer as a Character can ask for Attack, TakeDamage and LevelUp, but not AddArrow.
  • The type you hold an object as decides what you can ask of it; the object itself decides how it does it.

Through each day, Chloe goes from class, to rehearsal with the drama club, to an intense volleyball practice.

Chloe on her way through a busy day

Scholar

In class, her teacher treats her as a student. She's expected to study, and to take tests.

Singer

Chloe singing on stage

At rehearsal, she's a singer. She's expected to know her part, to sing it, and to remember her lines.

Athlete

Chloe playing volleyball

At volleyball, her teammates count on her as an athlete. She needs to serve well and hit hard.

Each role sees only part of her

When the teacher hands out a test, Chloe can still sing and still play volleyball. But the teacher is only thinking of her as a student, so the teacher only asks student things of her: study, take the test. Asking her to serve a volleyball in the middle of math class would make no sense.

That's the heart of polymorphism: you focus on the form that matters right now, and ignore the rest. The object doesn't change; what you're looking at does.

The same in code

When code holds an Archer as a Character, it can only ask for what every character can do:

Seen as You can ask it to You can't ask it to
Character Attack, TakeDamage, LevelUp AddArrow: not every character has arrows
Archer Everything a character can do, plus AddArrow

The archer still has its arrows. But code that only knows it as a character can't count on arrows, because a wizard or a knight wouldn't have any.

Check yourself

1 question to try on the lesson page.

So what

Each role sees only the part of an object it needs. In C#, the type you hold an object as decides what you can ask of it, and the object itself decides how it does it.

Key terms

Cheat sheets