#676 – An Overridden Method Can Itself Be Overridden
September 21, 2012 1 Comment
To get polymorphic behavior for a method in a derived class, you need to mark the method in the base class as virtual and the method in the derived class as override. This allows the method in the derived class to be called at runtime, even when referenced by a variable whose type is the base class.
public class Dog { public virtual void Bark() { Console.WriteLine(" Dog.Bark"); } } public class Terrier : Dog { public override void Bark() { Console.WriteLine(" Terrier is barking"); } }
The Bark method in Terrier overrides the version in Dog. But the override method also indicates that the Bark method can itself be overridden in a class that derives from Terrier.
public class JRT : Terrier { public override void Bark() { Console.WriteLine(" JRT is barking"); } }
The Bark method is now polymorphic across all three types.
An alternative is to only call the virtual method on-demand. This can be accomplished by providing the resources that are dependant on the virtual method to a class and/or its derived types via public or protected properties on the base class. The properties can check whether the resources have been initialized. If they haven’t, the property can call the virtual method once, caching the result for subsequent access.