Abstract Class in C#

Abstract classes define base classes in a hierarchy. An abstract class is an incomplete class; you can't create an instance of an abstract class. If you try, you will get a compile error. So you need to subclass an abstract class and create an instance of subclass to call an abstract class's methods.

Features

The following are the features of an abstract class:

  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • A non-abstract class is derived from an abstract class an must include an actual implementation of all the inherited abstract methods and accessors.
  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.

Now I will explain with an example. Here I declaed an astract class named fourwheeler containing a method explain(). And a class called maruti derived from the abstract class and I created an object of the derived class inside a main() function and call the abstract class's methods.

  1. namespace AbstractClasses  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.            maruti maru = new maruti();  
  8.      Console.WriteLine(maru.explain());  
  9.      Console.ReadLine();  
  10.         }  
  11.     }  
  1. abstract class fourwheeler  
  2.     {  
  3.         public virtual string explain()  
  4.         {  
  5.            // Console.WriteLine("fffffffffffffff");  
  6.            return "Not much is known about this four wheeler car!";  
  7.         }  
  8.     }  
  9.   
  10.     class maruti : fourwheeler  
  11.     {  
  12.   
  13.     }  
It shows as output:

“Not much is known about this four wheeler car!”

Now if I add the explain() method to the maruti class like:
  1. class maruti : fourwheeler  
  2.     {  
  3.             string result = base.explain();  
  4.             result += " it is Maruti";  
  5.             return result;  
  6.     }  
Then the output will be:

“Not much is known about this four wheeler car! It is maruti"

If try to make an object of the abstract class then we will get an error like:


 

Up Next
    Ebook Download
    View all
    Learn
    View all