Polymorphism
There are two powerful aspects to inheritance. One is code reuse. When you create a ListBox
class, you're able to reuse some of the logic in the base (Control
) class.
What is arguably more powerful, however, is the second aspect of inheritance: polymorphism. Poly means "many" and morph means "form." Thus, polymorphism refers to being able to use many forms of a type without regard to the details.
When the phone company sends your phone a ring signal, it doesn't know what type of phone is on the other end of the line. You might have an old-fashioned Western Electric phone that energizes a motor to ring a bell, or you might have an electronic phone that plays digital music.
As far as the phone company is concerned, it knows only about the "base type" Phone
and expects that any "instance" of this type knows how to ring. When the phone company tells your phone to ring, it simply expects the phone to "do the right thing." Thus, the phone company treats your phone polymorphically.
Creating Polymorphic Types
Because a ListBox
is-a Control
and a Button
is-a Control
, we expect to be able to use either of these types in situations that call for a Control
. For example, a form might want to keep a collection of all the instances of Control
it manages so that when the form is opened, it can tell each of its Control
s to draw itself. For this operation, the form doesn't want to know which elements are listboxes and which are buttons; it just wants to tick through its collection and tell ...
Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.