#348 – Virtual Methods Support Polymorphism
June 17, 2011 2 Comments
In C#, polymorphism is implemented using virtual methods. A virtual method has an implementation in the base class that can be overridden in a derived class. When the method is invoked on an object of the base class’ type, the specific method to be called is determined at run-time based on the type of the underlying object.
A virtual method is defined in the base class using the virtual keyword.
public class Dog { public virtual void Bark() { Console.WriteLine("Generic dog {0} says Woof", Name); } }
A virtual method is overridden in a derived class using the override keyword.
public class Terrier : Dog { public override void Bark() { Console.WriteLine("Terrier {0} is barking", Name); } }
This allows polymorphic behavior when invoking the Bark method.
Dog jack = new Terrier("Jack", 15); jack.Bark(); // Terrier.Bark called, rather than Dog.Bark