#678 – A Sealed Method Cannot Be Overridden

When you override a method, you create a virtual method that behaves polymorphically.  The base class defines the method using the virtual keyword and you define the method in your child class using the override keyword.

When you use the override keyword, your method can itself be overridden in a child class.

If you want to override a method in a base class, but also prevent any derived classes from overriding your method, you can use the sealed keyword to indicate that a child class must use the new keyword, rather than overriding your method.

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("  Dog.Bark");
        }
    }

    public class Terrier : Dog
    {
        public sealed override void Bark()
        {
            Console.WriteLine("  Terrier is barking");
        }
    }

    public class JRT : Terrier
    {
        public new void Bark()
        {
            Console.WriteLine("  JRT is barking");
        }
    }
Advertisement

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

One Response to #678 – A Sealed Method Cannot Be Overridden

  1. George says:

    Good job here Sean. I seal overrides in cases like this:
    (i) the method’s implementation is nontrivial – it has bulk or intellectual weight. Anyone considering overriding, but faced with the sealed restriction, should inherit some other class. Helicopter would have sealed Propel() to prevent people from inheriting JumboJet : Helicopter.
    (ii) the method like A(object x) merely calls a more strongly typed virtual method B(MyClass c) introduced in this class, ala B((MyClass)x).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: