Abstract & Sealed Classes

Abstract & Sealed Classes   



The abstract modifier is used to indicate that a class is incomplete and intended only to be a base class of other classes. An abstract class differs from a non-abstract class in the following ways:

  1. An abstract class cannot be instantiated, and it is an error to use the new operator on an abstract class.

  2. An abstract class is permitted (but not required) to contain abstract methods and accessors.

  3. An abstract class cannot be sealed.

  4. When a non-abstract class is derived from an abstract class, the non-abstract class must include actual implementations of all inherited abstract methods and accessors. Overriding the abstract methods and accessors provides such implementations.


Abstract Methods

When an instance method declaration includes an abstract modifier, the method is said to be an abstract method. An abstract method is implicitly also a virtual method.

An abstract declaration introduces a new virtual method but does not provide an implementation of the method. Instead, non-abstract derived classes are required to provide their own implementation by overriding the method. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon.

Abstract method declarations are only permitted in abstract classes. It is an error for an abstract method declaration to include any one of the static, virtual, or override modifiers.


Sealed Classes 

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class.

A sealed class cannot also be an abstract class. The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain run-time optimizations. In particular, because a sealed class is known to never have any derived classes, it is possible to transform virtual function member invocations on sealed class instances into non-virtual invocations. 


Sealed Methods

When an instance method declaration includes a sealed modifier, the method is said to be a sealed method. A sealed method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of the method.

An override method can also be, marked with sealed modifier. Use of this modifier prevents a derived class from further overriding the method. The sealed modifier can only be used in combination with the override modifier.

 

From: http://www.funducode.com/csharp/oops/oops5.htm
posted @ 2004-02-17 14:07  dudu  阅读(1238)  评论(1编辑  收藏  举报