Virtual Methods and Override Modifier in C#
Virtual methods are meant to be re-implemented in derived classes. The C# language provides the override modifier for this purpose. This keyword specifies that a method replaces its virtual base method.
Whereas a virtual method introduces a new method, an override method specializes an existing inherited virtual method by providing a new implementation of that method.
Example
This program illustrates the difference between an override method in a derived class, and a method that is not an override method. It does nothing useful but helps us learn about override methods.
In the example, the class A is the base class. It has the virtual method Y. In class B, we override Y. In class C, we implement Y but do not specify that it overrides the base method.
using System;
class A
{
public virtual void Y()
{
// Used when C is referenced through A.
Console.WriteLine("A.Y");
}
}
{
public virtual void Y()
{
// Used when C is referenced through A.
Console.WriteLine("A.Y");
}
}
class B : A
{
public override void Y()
{
// Used when B is referenced through A.
Console.WriteLine("B.Y");
}
}
{
public override void Y()
{
// Used when B is referenced through A.
Console.WriteLine("B.Y");
}
}
class C : A
{
public void Y() // Can be "new public void Y()"
{
// Not used when C is referenced through A.
Console.WriteLine("C.Y");
}
}
{
public void Y() // Can be "new public void Y()"
{
// Not used when C is referenced through A.
Console.WriteLine("C.Y");
}
}
class Program
{
static void Main()
{
// Reference B through A.
A ab = new B();
ab.Y();
{
static void Main()
{
// Reference B through A.
A ab = new B();
ab.Y();
// Reference C through A.
A ac = new C();
ac.Y();
}
}
A ac = new C();
ac.Y();
}
}
Result
B.Y
A.Y
A.Y
In this example, the A type is used to reference the B and C types. When the A type references a B instance, the Y override from B is used. But when the A type references a C instance, the Y method from the base class A is used.
No comments:
Post a Comment