3.13. Sealing a Class

To explicitly prevent derivation from a class, we specify the sealed keyword:

sealed public class BinaryTree { ... }

An attempt to inherit from a sealed class triggers a compile-time error:

// error: BinaryTree is a sealed class
public class RedBlackTree : BinaryTree { ... }

The sealed keyword cannot be applied to either a struct, which is already implicitly sealed, or class declared as abstract, which requires the inherited classes to provide a concrete implementation.

Why do we seal a class?

There is the philosophical aspect, of course. We're making a statement as to our perceived use of the class.

Unfortunately, our perception may be of limited perspicacity. For example, in the next chapter we will need to extend ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.