Thursday, April 23, 2015

Abstract Class in C# and Abstract VS Virtual

Abstract Class is one of the important idea of OOP. It is a special class that is not instantiated i.e. it represents only as base class from which you will not permitted to create objects. But you can inherit the abstract class to use it. Abstract Class consists of either abstract or non-abstract members or both. That means it may contains variables, constructors, functions or properties like other classes as well as abstract members. 

Now the questions is? What is abstract member? A member preceded with a keyword abstract with no definition in the base class, called abstract member. A derived class should override the abstract members of a base class to use it. Look at the following example:
public abstract class TestAbstractClass
{
     private string firstName;
     private string middleName;
     private string lastName;

     public TestAbstractClass(string firstName, string middleName, string lastName)
     {
          this.firstName = firstName;
          this.middleName = middleName;
          this.lastName = lastName;
     }

     public string GetFullName()
     {
          return firstName + " " + middleName + " " + lastName;
     }

     public abstract string ReverseName();
}
In this example, the abstract class('TestAbstractClass') contains only one abstract member function 'ReverseName()' and few non-abstract members like other classes. If any class want to inherit this abstract class, then that class should have to define(override) the abstract function 'ReverseName()' of 'AbsClass'. Look at the following class named 'SubAbsClass' which inherit the 'TestAbstractClass':
class SubAbsClass : TestAbstractClass
{
        public SubAbsClass(string firstName, string middleName, string lastName): base(firstName,
        middleName,lastName)
        {
        }       
        public override string ReverseName()
        {
              string fullName = GetFullName();
              string reverseName = "";
              for (int count = fullName.Length - 1; count >= 0; count--)
                   reverseName += fullName[count];
              return reverseName;
        }

}
Here, the derive class 'SubAbsClass' contains the definition of abstract function 'ReverseName()' of the base class 'TestAbstractClass'.

# We know that a member function preceded with a virtual keyword(virtual function) also override in derive class, then what is the difference between abstract and virtual functions?
  • Abstract methods have no implementation in the base class and must be overridden in the derive class. On the other hand, virtual methods may have implementation in the base class and can be overridden in derive class but it doesn't have to be overridden.
  • We cannot call base.method() for abstract methods but we can call for virtual methods.