#675 – Polymorphic Behavior Requires virtual / override Combination

Recall that polymorphism means that the type of an object at run-time is used to decide what method to call, rather than the static type of the variable that references that object.

In C#, a method behaves polymorphically if and only if the method in the base class is defined as virtual and the method in the derived class is defined as override.  

For example, if Terrier inherits from Dog, we can declare a Dog.Bark method as virtual and a Terrier.Bark method as override.  We then get polymorphic behavior:

Terrier t = new Terrier("Jack");
Dog d = t;

// Polymorphic behavior =
//   Terrier's implementation of Bark is called,
//   because type of object referenced by d is
//   determined at runtime.
d.Bark();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #675 – Polymorphic Behavior Requires virtual / override Combination

  1. Pingback: #676 – An Overridden Method Can Itself Be Overridden « 2,000 Things You Should Know About C#

  2. Pingback: #678 – A Sealed Method Cannot Be Overridden « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: