DekGenius.com
Team LiB   Previous Section   Next Section

11.5 Sealed Classes

The opposite side of the design coin from abstract is sealed. In contrast to an abstract class, which is intended to be derived from and to provide a template for its subclasses to follow, a sealed class does not allow classes to derive from it at all. The sealed keyword placed before the class declaration precludes derivation. Classes are most often marked sealed to prevent accidental inheritance.

If the declaration of Window in Example 11-3 is changed from abstract to sealed (eliminating the abstract keyword from the DrawWindow() declaration as well), the program fails to compile. If you try to build this project, the compiler returns the following error message:

'ListBox' cannot inherit from sealed class 'Window'

among many other complaints (such as that you cannot create a new protected member in a sealed class).

Microsoft recommends using sealed "when it will not be necessary to create derived classes"[1] and also when your class consists of nothing but static methods and properties.

[1] Visual Studio .NET Combined Collection: Base Class Usage Guidelines.

    Team LiB   Previous Section   Next Section