virtual methods
In this chapter you will learn:
Get to know virtual methods
A virtual member, marked by the virtual
keyword, can be overriden by its subclasses.
The method, property, indexer and event can be virtual.
A virtual method is declared as virtual in a base class and it is redefined
in one or more derived classes.
When redefining a virtual method in the derived class,
the override
modifier is used.
When overriding a method, the type signature of the method cannot be changed. A virtual method cannot be static or abstract.
The following code shows how to use the virtual method
to provide the different implementation of the Area
.
using System;// j ava 2 s .c o m
class Shape{
public virtual double Area{
get{
return 0;
}
}
}
class Rectangle:Shape{
public int width;
public int height;
public override double Area{
get{
return width * height;
}
}
}
class Circle:Shape{
public int radius;
public override double Area{
get{
return 3.14 * radius * radius;
}
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.width = 4;
r.height = 5;
Circle c = new Circle();
c.radius = 6;
Console.WriteLine(r.Area);
Console.WriteLine(c.Area);
}
}
The output:
C# requires that the virtual and override must have the same signature, accessor and return type.
virtual methods from parent classes
When a virtual method is not overridden, the base class method is used.
using System; /*from j a v a 2 s . com*/
class BaseClass {
// Create virtual method in the base class.
public virtual void who() {
Console.WriteLine("who() in BaseClass");
}
}
class Derived1 : BaseClass {
// Override who() in a derived class.
public override void who() {
Console.WriteLine("who() in Derived1");
}
}
class Derived2 : BaseClass {
// This class does not override who().
}
class MainClass {
public static void Main() {
BaseClass baseOb = new BaseClass();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
BaseClass baseRef; // a base-class reference
baseRef = baseOb;
baseRef.who();
baseRef = dOb1;
baseRef.who();
baseRef = dOb2;
baseRef.who(); // calls BaseClass's who()
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: