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 the BitArray collection class. However, the implementers have declared it as sealed, preventing inheritance. That's a real problem. Philosophy by itself is a poor design strategist!

There has to be a better reason for sealing a class. And there is: It can improve the performance of our classes.

Ordinarily the invocation of a virtual function or virtual accessor is unable to be resolved until runtime because the object through which we invoke the virtual member may refer not to an object of its class, but to an object of an unknown class derived from it. When we seal a class, we eliminate the unknown aspect of the invocation.

The invocation of a virtual member through an object of a sealed class can be resolved statically at compile time. Not only is the virtual mechanism unnecessary, but the opportunity for inline expansion, which is a compile-time optimization, becomes possible as well. This can significantly improve the performance of heavily used classes, such as that of the string and collection classes.

When an abstraction requires optimal performance but is not appropriate as a value type, a sealed class is a potential alternative design. A sealed class is still created on the managed heap, but its virtual interface is eliminated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.104