#334 – A Base Class Variable Can Refer to Instances of Derived Classes

A variable whose type is a particular class can refer to instances of that class or it can refer to instances of any derived classes.

Assume that we have a Dog class (base class) and a Terrier class (derived class) that inherits from Dog.  A variable of type Dog can then refer to either a Dog or a Terrier.

Dog kirby = new Dog("Kirby", 15);

// Dog variable can point to Terrier
Dog jack = new Terrier("Jack", 17, "Surly");

// Terrier variable can also point to Terrier
Terrier bubba = new Terrier("Bubba", 2, "Happy");

Notice that even though the variable jack is of type Dog, it still points to an instance of a Terrier.

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.

One Response to #334 – A Base Class Variable Can Refer to Instances of Derived Classes

  1. Pingback: #335 – Accessing a Derived Class Using a Base Class Variable « 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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers