Tuesday, March 16, 2010

Virtual and Override Methods

To use the polymorphic methods introduced in the preceding section, declare the DrawWindow method with the keyword virtual in the base class:
public virtual void DrawWindow()
{
       //The method definition in the base class.
}
Then, in each of the classes that inherit the base class, declare a DrawWindow method using the keyword override:
public override void DrawWindow()
{
    //The method definition in one of the derived classes.
}
The method declared with the keyword override is called an override method. It can override another method that has the same name, signature, and accessibility in the base class. When we override a method, we can change its original behavior in the derived class. An override method can override any of the methods declared with the following modifiers:
•    Virtual
•    Abstract
•    Override
When a virtual method in a derived class has the same name, accessibility, and signature as that of another method in the base class but is not qualified with the override modifier, it simply hides the method of the base class. To make the method override the one in the base class, you must modifier its declaration with the keyword override. An abstract method is implicitly a virtual method, and therefore, it can be overridden without using the virtual modifier.
Note: we cannot use the virtual modifier with the following modifiers:
Static, abstract, virtual, or new.

No comments:

Post a Comment