#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.

Advertisements