Saturday, December 15, 2012

Method Overriding

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

In this example, the class Square must provide an overridden implementation of Area because Area is inherited from the abstract ShapesClass:


abstract class ShapesClass
{
    abstract public int Area();
}

class Square : ShapesClass
{
    int x, y;
    // Because ShapesClass.Area is abstract, failing to override
    // the Area method would result in a compilation error.
    public override int Area()
    {
        return x * y;
    }
}

Points to remember : 
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. 
You cannot override a non-virtual or static method. The overridden base method must be virtualabstract, or override.
An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
You cannot use the modifiers newstaticvirtual, or abstract to modify an override method.
An overriding property declaration must specify the exact same access modifier, type, and name as the inherited property, and the overridden property must be virtualabstract, or override.
The override, virtual, and new keywords can also be applied to properties, indexers, and events.

No comments:

Post a Comment