#347 – Another Example of Polymorphism

The power of polymorphism is that you can invoke methods in derived classes using a reference to the base class.

Assume that you have a Dog base class and a series of classes that derive from Dog.  You might define a generic Bark method in the base class and then a Bark method specific to each breed in each of the derived classes.

You can write a method that takes any Dog as a parameter and invokes that dog’s Bark method.

    static void BarkAndTell(Dog d)
        {
            d.Bark();
            Console.WriteLine("{0} just barked", d.Name);
        }

You can pass instances of the derived classes into this method.

            Terrier jack = new Terrier("Jack", 15);
            Shepherd kirby = new Shepherd("Kirby", 12);

            BarkAndTell(jack);
            BarkAndTell(kirby);

Polymorphism ensures that the  Bark method in the appropriate subclass is called, even though we’re referring to the instance using a variable whose type is the parent class (Dog).

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

%d bloggers like this: