Abstract Class In C#

GrowthLadder

 

An abstract class is an incomplete class or special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules on what the derived classes must implement when they inherit an abstract class.

We can use an abstract class as a base class and all derived classes must implement abstract definitions. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding the abstract method is in the non-Abstract class. We can derive this class in another class and again we can override the same abstract method with it.

Abstract Method: A method that is declared abstract, has no “body” and declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it.

Syntax:

public abstract void mytest();

 

Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically used to define a base class in the class hierarchy. Or in other words, an abstract class is an incomplete class or special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions.

Syntax:

abstract class MyAbc{}

C# Abstract Class Features

  • An abstract class can inherit from a class and one or more interfaces.
  • An abstract class can implement code with non-Abstract methods.
  • An Abstract class can have modifiers for methods, properties, etc.
  • An Abstract class can have constants and fields.
  • An abstract class can implement a property.
  • An abstract class can have constructors or destructors.
  • An abstract class cannot be inherited from structures.
  • An abstract class cannot support multiple inheritances.

 

Contents

An abstract class may contain the following,

  • Non-Abstract Method
  • Abstract method
  • Non-Abstract Property
  • Abstract Property
  • Constructor
  • Destructor

Example 1 :

abstract class Demo  
    {  
        public int Int1 { get; set; } //Non Abstract property  
  
        public abstract int Int2  //Abstract Property  
        {  
            get;  
            set;  
        }  
  
        public  Demo()  //Constructor  
        {  
            Console.WriteLine("Demo Constructor");  
        }  
  
        public void Method1()   //Non Abstract Method  
        {  
            Console.WriteLine("Demo Method1");  
        }  
  
        public abstract void Method2();  //Abstract Method  
  
         ~Demo()  //Destructor  
        {  
            Console.WriteLine("Demo Destructor");  
        }  
          
    }  
  
    class Drived : Demo  
    {  
        public int Val;  
        public override int Int2  
        {  
            get  
            {  
                return Val;  
            }  
            set  
            {  
                Val=value;  
            }  
        }  
  
        public override void Method2()  
        {  
            Console.WriteLine("Drived Method2");  
        }  
    }  
    class Program  
    {  
        static unsafe void Main(string[] args)  
        {  
  
            Drived Dr = new Drived();  
            Dr.Int1 = 10;  
            Dr.Int2 = 20;  
            Dr.Method1();  
            Dr.Method2();  
            Console.ReadLine();  
        }     
  
    }

 

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract or included in an abstract class, must be implemented by classes that derive from the abstract class.

The following is another example of an abstract class that will enhance the concept of abstract classes even more.

Example 2 :

//Abstract class  
    abstract class Shape1  
    {  
  
        protected float R, L, B;  
  
        //Abstract methods can have only declarations  
        public abstract float Area();  
        public abstract float Circumference();  
    }  
  
    class Rectangle1 : Shape1  
    {  
        public void GetLB()  
        {  
            Console.Write("Enter  Length  :  ");  
  
            L = float.Parse(Console.ReadLine());  
  
            Console.Write("Enter Breadth : ");  
  
            B = float.Parse(Console.ReadLine());  
        }  
  
  
        public override float Area()  
        {  
            return L * B;  
        }  
  
        public override float Circumference()  
        {  
            return 2 * (L + B);  
        }    
    }  
  
    class Circle1 : Shape1  
    {  
  
        public void GetRadius()  
        {  
  
            Console.Write("Enter  Radius  :  ");  
            R = float.Parse(Console.ReadLine());  
        }  
  
        public override float Area()  
        {  
            return 3.14F * R * R;  
        }  
        public override float Circumference()  
        {  
            return 2 * 3.14F * R;
        }  
    }  
  
    class Program  
    {  
        public static void Calculate(Shape1 S)  
        {  
  
            Console.WriteLine("Area : {0}", S.Area());  
            Console.WriteLine("Circumference : {0}", S.Circumference());  
        }  
        static void Main(string[] args)  
        {  
  
            Rectangle1 R = new Rectangle1();  
            R.GetLB();  
            Calculate(R);  
  
            Console.WriteLine();  
  
            Circle1 C = new Circle1();  
            C.GetRadius();  
            Calculate(C);  
            Console.ReadLine();  
        }     
    }

Some Important Points About Abstract Classes

private

An abstract method cannot be private as in the following,

abstract  class  Demo()  

    {  

       private abstract void Call();  

    }  

If we use the private access specifier for an abstract method then it will throw an error, because if we declare an abstract method as private then the derived classes cannot override it and that is inconsistent with the rules of abstract classes. So we cannot use have a private access specifier for an abstract method.

The same

An access specifier should be the same as in the following,

abstract class Demo()  

    {  

       abstract  protected   void Call();  

    }  

  

    class Drived:Demo  

    {  

        protected override void Call()  

{  

    //Code of Class  

}  

The access modifier of the abstract method should be the same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.

sealed

An abstract class cannot be a sealed as in the following,

abstract sealed class Demo()  

    {  

    }  

Because If we declare an abstract class as sealed then, according to the property of the sealed keyword, the demo class cannot be inherited but, according to the property of the abstract keyword, an abstract class should be inherited. So a conflict will exist. So an abstract class cannot be declared as sealed.

virtual

An abstract method cannot have the modifier virtual as in the following,

abstract  class Demo()  

    {  

        abstract virtual public void Call();  

  

        virtual  abstract  public void Call();  

  };  

An abstract method cannot have the modifier virtual because an abstract method is implicitly virtual.

 

Abstract class inherited from Interface(s)

Example  3 :

public interface IFace  
    {  
        void  Call();  
        void  Demo();  
    }  
  
    public abstract class IDriv : IFace  
    {  
        public void  Call()  
        {  
            Console.WriteLine("Call Method");  
        }  
        public abstract void  Demo();  
    }  
  
  
    public class Drived:IDriv  
    {  
        public override void Demo()  
        {  
            Console.WriteLine("Demo Method");  
        }  
    }  
      
    class Program  
    {  
         
        static void Main(string[] args)  
        {  
            Drived Dr = new Drived();  
            Dr.Call();  
            Dr.Demo();  
              
            Console.ReadLine();  
        }  
  
        }

 

An Abstract Class can Contain Constant and Readonly Variables

Example 4 :

abstract class Demo  
    {  
        public const int Int_ = 30;  
        public readonly int Int2;  
  
        public  Demo()  
        {  
            Int2 = 100;  
        }  
  
        abstract public void Call();  
    }  
  
    class Drived : Demo  
    {  
        public override void Call()  
        {  
            Console.WriteLine("  Int_ ={0}  Int2= {1}", Int_, Int2);  
        }  
    }  
    class Program  
    {  
          
        static void Main(string[] args)  
        {  
            Drived Dr = new Drived();  
            Dr.Call();  
            Console.ReadLine();  
        }  
  
        }

 

Sealed Classes and Class Members

Classes can be declared as sealed by putting the keyword sealed before the class definition.

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

A method, indexer, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.

Example 5 :

abstract class Demo  
    {  
        public const int Int_ = 30;  
        public readonly int Int2;  
  
        public  Demo()  
        {  
            Int2 = 100;  
        }  
  
        abstract public void Call();  
    }  
  
    class Drived : Demo  
    {  
        public  override void Call()  
        {  
            Console.WriteLine("  Int_ ={0}  Int2= {1}", Int_, Int2);  
        }  
    }  
  
    class Assign : Drived  
    {  
        public override    void Call()  
        {  
            Console.WriteLine("pankaj");  
        }  
    }  
    class Program  
    {  
          
        static void Main(string[] args)  
        {  
            Assign  Dr = new Assign();  
            Dr.Call();  
            Console.ReadLine();  
        }  
  
        }

 

 

In the preceding example we have an abstract class Demo and the class Drived inherits the Demo class. So it can override the abstract method of the Demo class. In the example the Assign class inherits the Drived class so it can also override the abstract method of the Demo class due to Multilevel Inheritance. If we want to avoid this problem then we can use the “Sealed“  Keyword in the Drived class. Like this,

Example 6 :

abstract class Demo  
    {  
        public const int Int_ = 30;  
        public readonly int Int2;  
  
        public  Demo()  
        {  
            Int2 = 100;  
        }  
  
        abstract public void Call();  
    }  
  
    class Drived : Demo  
    {  
        public  sealed  override void Call()     //Use of sealed Keyword  
        {  
            Console.WriteLine("  Int_ ={0}  Int2= {1}", Int_, Int2);  
        }  
    }  
  
    class Assign : Drived  
    {  
        public override    void Call()  
        {  
            Console.WriteLine("pankaj");  
        }  
    }  
    class Program  
    {  
          
        static void Main(string[] args)  
        {  
            Assign  Dr = new Assign();  
            Dr.Call();  
            Console.ReadLine();  
        }  
  
        }

 

When Should we use an Abstract Class

  • When independency of a class is not required in your application.
  • If there are certain members/behaviors that are common to all classes, these should be placed inside the abstract class.
  • If we want to provide some method to a base class that must be implemented in a derived class then we can use an abstract class and make the method abstract. Which we want to implement in the derived class.

 

 

 

Arijit Banerjee

Microsoft Certified: Azure AI Engineer Associate
Published On : 11 May, 2021