A virtual method can be
redefined. The virtual keyword designates a method that is overridden in
derived classes. We can add derived types without modifying the rest of the
program. The runtime type of objects thus determines behavior.
Virtual key should not be used with Private keyword.
Virtual key should not be used with Private keyword.
Example
This program introduces two classes, A and B.
Class A has a public virtual method called Test. Class B, meanwhile, derives
from class A and it provides a public override method called Test as well.
Tip: The
virtual modifier tells the compiler that when any class derived from class A is
used, an override method should be called.
Program that introduces virtual method: C#
using System;
class A
{
public virtual void Test()
{
Console.WriteLine("A.Test");
}
}
class B : A
{
public override void Test()
{
Console.WriteLine("B.Test");
}
}
class Program
{
static void Main()
{
// Compile-time type is A.
// Runtime type is A as well.
A ref1 = new A();
ref1.Test();
// Compile-time type is A.
// Runtime type is B.
A ref2 = new B();
ref2.Test();
}
}
Output
A.Test
B.Test
With virtual methods, the
runtime type is always used to determine the best method implementation. In
Main, ref1 has a compile-time and runtime type of A. On the other hand, ref2
has a compile-time type of A but a runtime type of B.
No comments:
Post a Comment