Section 11.5. Sealed Classes


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 you changed the declaration of Window in Example 11-3 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 type 'Window' 

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

Microsoft recommends using sealed when you know that you won't need to create derived classes, and also when your class consists of nothing but static methods and properties.



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net