C Sharp

Virtual Methods

As we saw in Chapter 5, you can derive one class from another so that one class can inherit and build on the capabilities of an existing class. Because I hadn't discussed methods yet, that discussion touched on the inheritance of fields and methods only. In other words, I didn't look at the ability to modify the base class's behavior in the derived class. This is done by using virtual methods and is the subject of this section.

Method Overriding

Let's first look at how to override the base class functionality of an inherited method. We'll begin with a base class that represents an employee. To keep the example as simple as possible, we'll give this base class a single method called CalculatePay with the body of this method doing nothing more than letting us know the name of the method that was called. This will help us determine which methods in the inheritance tree are being called later.

class Employee
{
    public void CalculatePay()
    {
        Console.WriteLine("Employee.CalculatePay()");
    }
}

Now, let's say that you want to derive a class from Employee and you want to override the CalculatePay method to do something specific to the derived class. To do this, you need to use the new keyword with the derived class's method definition. Here's the code to show how easy that is: -

using System;
class Employee
{
    public void CalculatePay()
    {
        Console.WriteLine("Employee.CalculatePay()");
    }
}
class SalariedEmployee : Employee
{
    // The new keyword enables you to override the
    // base class' implementation.
    new public void CalculatePay()
    {
        Console.WriteLine("SalariedEmployee.CalculatePay()");
    }
}
class Poly1App
{
    public static void Main()
    {
        Poly1App poly1 = new Poly1App();
        Employee baseE = new Employee();
        baseE.CalculatePay();
        SalariedEmployee s = new SalariedEmployee();
        s.CalculatePay();
    }
}

Compiling and executing this application generates the following output: -

c:\>Poly1App
Employee.CalculatePay()
Salaried.CalculatePay()