#347 – Another Example of Polymorphism
June 16, 2011 Leave a comment
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).