#676 – An Overridden Method Can Itself Be Overridden

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.

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

One Response to #676 – An Overridden Method Can Itself Be Overridden

  1. las artes says:

    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.

Leave a comment