Using Sealed to Prevent Inheritance


As powerful and useful as inheritance is, sometimes you will want to prevent it. For example, you might have a class that encapsulates the initialization sequence of some specialized hardware device, such as a medical monitor. In this case, you don’t want users of your class to be able to change the way the monitor is initialized, possibly setting the device incorrectly. Whatever the reason, in C# it is easy to prevent a class from being inherited by using the keyword sealed.

To prevent a class from being inherited, precede its declaration with sealed. As you might expect, it is illegal to declare a class as both abstract and sealed because an abstract class is incomplete by itself and relies upon its derived classes to provide complete implementations.

Here is an example of a sealed class:

 sealed class A {   // ... } // The following class is illegal. class B : A { // ERROR! Can't derive class A   // ... }

As the comments imply, it is illegal for B to inherit A because A is declared as sealed.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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