#678 – A Sealed Method Cannot Be Overridden
September 25, 2012 1 Comment
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"); } }
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).