Before reading this article, please go through the following articles:

  1. Object Oriented Programming Using C#: Part 1
  2. Object Oriented Programming Using C#: Part 2
  3. Object Oriented Programming Using C#: Part 3
  4. Object Oriented Programming Using C#: Part 4
  5. Object Oriented Programming Using C#: Part 5
  6. Object Oriented Programming Using C#: Part 6
  7. Object Oriented Programming Using C#: Part 7
  8. Object Oriented Programming Using C#: Part 8
  9. Object Oriented Programming Using C#: Part 9

  10. Object Oriented Programming Using C#: Part 10

  11. Learn OOP Interface Using C#

Virtual Methods

Dear reader today we will discuss another important component of OOP, virtual methods. I will explain this using a simple example. Fig (1.0) shows Class A having one virtual method AA and its implementation is a shirt with a yellow flower. Class B inherits Class A and overrides the method AA; its implementation is different since it wears a different shirt style with cap.

VirtualMethods.jpg

Fig (1.0)(Simple Virtual Example)

In simple words:

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as in a derived class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class.

Simple Example

VirtualMethods1.jpg

Output:

VirtualMethods2.jpg

Block A:

Block B:

Block C:

Real Example:

In this example we will create the small application that will calculate the tax of the gross pay. In our application we allow the tax exemption for employees whose age is greater than 50 years.

Step 1:

Create the new project with the name of LearnVirtualMethod.

VirtualMethods3.jpg

Step 2:

Design the form1 as shown in the picture.

VirtualMethods4.jpg

Step 3:

Create a new class with name of tax as in the following. Having one virtual method calculateTax.

VirtualMethods5.jpg
VirtualMethods6.jpg

Block A:

Block B:

Block C:

Step 4:

Enter the following code in the (Calculate Tax) button.

VirtualMethods7.jpg
Block A:

Step 5:

To execute the program press F5 and enter the gross pay 70000 and click on the button.

The calculated tax will be shown as in the following result.

VirtualMethods8.jpg

Step 6:

Now click the check box button and again click the click button Calculate tax.

You will get the following result.

VirtualMethods9.jpg