C# Abstract and Virtual Method – Inheritance Tutorial with Code

Abstract_vs_Virtual
In this chapter you will learn

  • What is Abstract Method?
  • What is Virtual Method?
  • How to use it in Inheritance?

What is Abstract and Virtual Method?

Abstract Method

Abstract methods are that type of method which is created only for signature only in base class. Means it is created in base class with abstract keyword but it has no body implementation. For example:

An abstract class must be overridden in child class with override keyword.

Point to be Noted

  1. An abstract modifier can be used with classes, methods, properties, indexers and events.
  2. If class contains abstract member then class must be created with abstract modifier. Example:
     




  3.  

  4. An abstract class must be overridden using override keyword in child class. If you miss to override them, program will raise compile time error.

     

     

  5. An abstract class cannot be instantiated. Means you cannot create object of abstract class with new keyword.
  6. An abstract method has no method body. The method declaration ends with semi colon (;) and after that there is no curly braces ({}).

     

     

Programming Example

In this programming example there is an abstract method sum() in abstract class baseclass. In the child class this abstract method is overridden with override keyword.

Output

Total Sum : 25
_

Virtual Method

There may be very long definition of Virutal Method but I kept it simple and short. A virtual method can be overridden or cannot be overridden by child class. It is upon programmer choice. It gives flexibility to direct use of virtual method or add additional functionality in it by overriding it.

Following example have a base class which has a virtual method message(). There is two child class is created. Child1 is overriding the virtual method and adding own message where child2 is displaying direct message of virtual method.

Programming Example

Output

I am child 1 class
I am base class Virtual Method
_

Summary

In this chapter you learned abstract and virtual method of C#. It becomes very useful in inheritance when you want to write code in strict disciplined manner. You can create signature of all the methods in abstract base class and force child class to implement them. Virtual Method gives you flexibility to write code in your choice. In the next chapter you will learn Constructors in Inheritance.


Leave a Reply

Your email address will not be published. Required fields are marked *