Abstract Class In C#

Today, we will learn about Abstract Class. Let’s start!!!

A class defined with Abstract keyword is simply Abstract Class. In simple words, we can say that a class especially designed to act as a base class for a number of classes is known as Abstract Class. Let’s take an example.

  1. static void Main(string[] args) {  
  2.     Person person = new Punjabi();  
  3.     Console.WriteLine("/*************Punjabi**************/");  
  4.     person.ICanSpeak();  
  5.     Console.WriteLine("\n");  
  6.     person.ICanWalk();  
  7.     person = new Tamil();  
  8.     Console.WriteLine("\n/*************Tamil**************/");  
  9.     person.ICanSpeak();  
  10.     Console.WriteLine("\n");  
  11.     person.ICanWalk();  
  12.     Console.ReadKey();  
  13. }  
  14. public abstract class Person {  
  15.     public void ICanWalk() {  
  16.         Console.Write("I can walk.");  
  17.     }  
  18.     public abstract void ICanSpeak();  
  19. }  
  20. public class Punjabi: Person {  
  21.     public override void ICanSpeak() {  
  22.         Console.Write("I can speak Punjabi.");  
  23.     }  
  24. }  
  25. public class Tamil: Person {  
  26.     public override void ICanSpeak() {  
  27.         Console.Write("I can speak Tamil.");  
  28.     }  
  29. }  
In this example, we have created an abstract class with a non-abstract method. The class "Person" will act as the base class when we inherit into another class. A Punjabi or Tamil can walk whether or not he/she speaks Punjabi or Tamil language. The output of the program will be as follows.


Some facts about Abstract Class.
  1. In an abstract class, we can define abstract method as well as non abstract methods.
  2. If we want to define an abstract method in abstract class, then we have to declare the method in abstract class without implementation. The declared abstract method must be implemented in derived class.


  3. We can’t instantiate the abstract class i.e. we can’t create object of abstract class.
  4. An abstract class can’t be sealed.
  5. We can inherit one abstract class into another abstract class. In that case, it is optional in the child class to implement the abstract method of base class. Let’s take an example.



    The output will be same in both the cases.

  6. An abstract class can’t be sealed because a sealed class is the last class in the inheritance hierarchy, and abstract classes are designed to act as base class.
  7. Abstract class can have constructor as well as destructor.

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now