Virtual methods and Abstract Class in C#

Virtual methods and Abstract Class

The main objective of virtual method is that, you can redefine it in one or more derived classes. You can use virtual keyword with method, property, indexer, or event. It allows these members to be overridden in a derived class. The implementation of a virtual member can be changed in a derived class by overriding these members (method, property, indexer, event). The process of redefining a virtual method in a derived class is called method overriding. It is also called as runtime polymorphism, late binding or dynamic binding. When overriding a method, the name, return type, and signature of the overriding method should be the same as the virtual method.

In C#, by default, all methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

It is not compulsory to override a virtual method in derived class. In multilevel hierarchy if a derived class does not provide its own version of a virtual method, then the one in the base class is used.

Example

using System;
namespace ConsoleApplication1
{
     class BaseClass
    {       
        public virtual void show()
        {
            Console.WriteLine("Base class method is called");
        }
    }
    class DerivedClass : BaseClass
    {        
         public override void show()
        {
            Console.WriteLine("DerivedClass method is called");
        }
    }
    class MostDerivedClass : DerivedClass
    {
         public override void show()
        {
            Console.WriteLine("MostDerivedClass  method is called");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass baseObj;
            MostDerivedClass obj = new MostDerivedClass();
            obj.show();
            baseObj = obj;
            baseObj.show();
            Console.ReadLine();
        }
    }
}


Output:
MostDerivedClass method is called
MostDerivedClass method is called

The above program creates a base class called BaseClass and two derived classes, called DerivedClass and MostDerivedClass. BaseClass have a method called show( ), and both the derived classes override it. Inside the Main( ) method, we have created two objects of type BaseClass (reference) and MostDerivedClass.

Please see the output carefully. You can call the derived class method by using reference of base class. It is main advantage of virtual and overriding (Run time binding).

Abstract class and abstract method

You can declare a class as abstract class, if it is incomplete class or you don’t know the complete functionality of class. The abstract modifier can be used with classes, methods, properties, indexers, and events. You cannot provide implementation if class member is abstract. Also you cannot create the object of abstract class.

Example

using System;
namespace ConsoleApplication1
{
    abstract class Shape
    {       
        public Shape()
        {
            Console.WriteLine("Constructor is called from abstract class");
        }       
        public abstract int Area(int length, int breath);       
    }
    class Rectangle : Shape
    {
        public override int Area(int length, int breath)
        {
            return length * breath;
        }           
    }    
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle obj = new Rectangle();
            Console.WriteLine("Enter the length of rectangle");
            int length=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the brath of rectangle");
            int breath = Convert.ToInt32(Console.ReadLine());
            int area = obj.Area(length, breath);
            Console.WriteLine("Area of rectangle ="+area);
            Console.ReadLine();
        }
    }
}


In the above program, if you not override the Area() method or trying to create object of Shape class, it will give you compile time error. It is mandatory to override abstract method in the derived class.

Key things about the abstract class:

  • You cannot create the object of abstract class (cannot be instantiated).
    Sealed modifier cannot be used with abstract class because sealed prevents the class from being inherited.
  • A non-abstract class which is derived from an abstract class must provide implementations of all inherited abstract methods.
  • You can create abstract property in base class and override it in derived class. Base class must be abstract class.

abstract class Shape
    {               
        // ………………
        // Your code
        public abstract int Length { get; }
        public abstract int Breath { get; }       
    }
    class Rectangle : Shape
    {
        public override int Length
        {
            get {
                        // ………………
                       // Your code
                  }
        }
        public override int Breath
        {
            get {
                         // ………………
                        // Your code
                  }
        }
    }


Key things about the abstract methods:
   
  • An abstract method is by default a virtual method.
  • Abstract methods cannot be declared as static, or virtual.
  • Abstract method must be written in abstract classes.
  • Abstract methods has no implementation (no method body)
public abstract void Area();