#346 – Polymorphism

Recall that polymorphism is one of the three core principles of object-oriented programming.

Polymorphism is the idea that the same code can act differently, depending on the underlying type of the object being acted upon.  The type of the object is determined at run-time, rather than at compile-time.

In C#, you can use a variable declared as a base type to refer to instances of one or more derived types.  Polymorphism allows you to call a method that exists in the base type but whose implementation exists in the derived types.  The appropriate method in the derived type will be called, based on the type of the object.

            Dog d;

            d = new Terrier("Jack", 15);
            d.Bark();      // Terrier.Bark is called

            d = new Shepherd("Kirby", 12);
            d.Bark();      // Shepherd.Bark is called
Advertisements