Abstract Class and Abstract Methods in C#

Abstract Class in C#

A method that does not have a body is called an abstract method and the class that is declared by using the keyword abstract is called an abstract class. If a class contains an abstract method, then it must be declared as abstract. In this article, we will discuss abstract class and abstract methods in details using some real-time examples.

What is an abstract class?

A class that is declared by using the keyword abstract is called an abstract class. An abstract class is a partially implemented class used for developing some of the operations of an object which are common for all next level subclasses.

So it contains both abstract methods, concrete methods including variables, properties, and indexers.

It is always created as superclass next to interface in object inheritance hierarchy for implementing common operations from an interface.

An abstract class may or may not have abstract methods. But if a class contains an abstract method then it must be declared as abstract.

An abstract class cannot be instantiated directly. It’s compulsory to create/derive a subclass from the abstract class in order to provide functionality to its abstract functions.

What is the abstract method?

A method that does not have a body is called an abstract method. It is declared with the modifier abstract. It contains only Declaration/signature and does not contain implementation/body/definition of the method.

An abstract function should be terminated with a semicolon. Overriding of an abstract function is compulsory.

Why should method have abstract keyword if it does not have a body?

In a class, we are allowed only to define a class with the body. Since we are changing its default behavior (means removing its body) it must have the abstract keyword in its prototype.

Characteristics of an abstract class

  1. An abstract class can contain both abstract methods and non-abstract (concrete) methods.
  2. It can contain both static and instance variables.
  3. The abstract class cannot be instantiated but its reference can be created.
  4. If any class contains abstract methods then it must be declared by using the keyword abstract.
  5. An abstract class can contain sealed methods but an abstract method or class cannot be declared as sealed.
  6. A subclass of an abstract class can only be instantiated if it implements all of the abstract methods of its superclass. Such classes are called concrete classes to differentiate them from abstract classes.
When should a class be declared as abstract?

A class should be declared as abstract

  1. If the class has any abstract methods
  2. If it does not provide implementation to any of the abstract methods it inherited
  3. If it does not provide implementation to any of the methods of an interface
When to use the abstract method?

Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways. Often the subclasses are required to fulfill an interface, so the abstract superclass might provide several of the interface methods, but leave the subclasses to implement their own variations of the abstract methods. Abstract classes can be thought of as part-complete templates that make it easier to write a series of subclasses.

Child class of abstract class:
  1. Implements all the abstract methods of the parent
  2. Then only we can consume non-abstract methods of the parent.

NOTE1: An abstract class can contain both abstract and non-abstract methods in it. If a child class of an abstract class wants to consume any non-abstract methods of its parent, should implement all abstract methods of its parent.

NOTE2: An abstract class is never usable to itself, because we cannot create the object of an abstract class. The members of an abstract class can be consumed only by the child class of the abstract class.

RULES OF ABSTRACT METHOD AND ABSTRACT CLASS:

RULE1: If a method does not have the body it should be declared as abstract using the abstract modifier else it leads to compile time error: “must declare a body because it is not marked abstract, extern, or partial”

public class Example
{
    // compile time error: must declare a body because it is not marked abstract, extern, or partial
    void m1(); 
}

RULE2: If a class has an abstract method it should be declared as abstract by using the keyword abstract else it leads to a compile-time error: ‘Example.m1()’ is abstract but it is contained in non-abstract class ‘Example’.

public class Example
{
    //'Example.m1()' is abstract but it is contained in non-abstract class 'Example'	
    public abstract void m1();
}

The correct syntax is

public abstract class Example
{
    public abstract void m1();
}

RULE3: If a class is declared as abstract it cannot be instantiated violation leads to compile time Error.

public abstract class Example
{
    public abstract void m1();
    public static void Main(String[] args)
    {
        //Cannot create an instance of the abstract class or interface 'Example'
        Example e = new Example();
    }
}

Error: Cannot create an instance of the abstract class or interface ‘Example’

RULE 4: The sub-class of an abstract class should override all abstract methods or it should be declared as abstract else it leads to the compile-time error:

namespace AbstractDemo
{
    public abstract class Example
    {
        public abstract void m1();
        public abstract void m2();
    }
    //'Sample' does not implement inherited abstract member 'Example.m2()'
    public class Sample : Example
    {
        public override void m1()
        {
            Console.WriteLine("m1 method");
        }
    }
}
Solutions:

Declare class as abstract as shown below

public abstract class Sample : Example
{
    public override void m1()
    {
        Console.WriteLine("m1 method");
    }
}

Override both abstract methods as shown below

public class Sample : Example
{
    public override void m1()
    {
        Console.WriteLine("m1 method");
    }
    public override void m2()
    {
        Console.WriteLine("m2 method");
    }
}
Why can abstract class not be instantiated?

Because it is not fully implemented the class as its abstract methods cannot be executed. If compiler allows us to create the object for an abstract class we can invoke the abstract method using that object which cannot be executed by CLR at runtime. Hence to restrict calling abstract methods, the compiler does not allow us to instantiate an abstract class.

Who will provide the implementation (body) for abstract methods?

Sub-class developers provide the body for abstract methods according to their business requirements. Basically, in projects, abstract methods (method prototype) are defined by the superclass developer and they are implemented by sub-class developer.

What type of member can we define in an abstract class?

We can define all static and non-static members including properties, fields, indexes and also abstract methods.

Will abstract class members be created when sub-class object is created?

Yes, its non-static members get memory when its concrete sub-class object is created.

How can we execute static and non-static concrete members of the abstract class?

Static members can be executed directly from its main method and its non-static members are executed by using its concrete sub-class object.

Can we declare an abstract method as static?

No, we are not allowed to declare an abstract method as static. It leads to Compile Time Error: illegal combination of modifier abstract and static.

If compiler allows us to declare it as static, it can be invoked directly which cannot be executed by CLR at runtime. Hence to restrict in calling abstract methods compiler does not allow us to declare an abstract method as static.

For example

namespace AbstractDemo
{
    public abstract class Example
    {
        //A static member 'Example.m1()' cannot be marked as override, virtual, or abstract
        public static abstract void m1(); 
        public abstract void m2();
    }
}
Can we declare an abstract method as sealed?

No, because it should be allowed to override in subclasses. It leads to Compile Time Error: cannot be sealed because it is not an override.

For example:

namespace AbstractDemo
{
    public abstract class Example
    {
        // 'Example.m1()' cannot be sealed because it is not an override
        public sealed abstract void m1();  
        public abstract void m2();        
    }
}
Can we declare an abstract method as private?

No, because it should be inherited to subclasses. It leads to Compile Time Error: virtual or abstract members cannot be private.

For example:

namespace AbstractDemo
{
    public abstract class Example
    {
        //'Example.m1()': virtual or abstract members cannot be private
        private abstract void m1(); 
        public abstract void m2();       
    }
}
Can we declare a concrete class as abstract?

Yes, it is allowed. Defining a class as abstract is a way of preventing someone from instantiating a class that is supposed to be extended first.

To ensure our class non-static members are only accessible via sub-class object we should declare the concrete class as abstract.

Let see an example for better understanding

namespace AbstractDemo
{
    Public abstract class Example
    {
        public static void m1()
        {
            Console.WriteLine("Example m1 method");
        }
        public void m2()
        {
            Console.WriteLine("Example m2 method");
        }
    }
}

Calling concrete abstract members from normal class:

namespace AbstractDemo
{
    public class Sample
    {
        static void Main(String[] args)
        {
            Example.m1();
            //CE: cannot be instantiated class Example
            Example e = new Example();
            //not possible
            e.m2();
        }
    }
}

Calling concrete abstract class members from sub-classes

namespace AbstractDemo
{
    public class Sample : Example
    {
        static void Main(String[] args)
        {
            Example.m1();
            Sample e = new Sample();
            e.m2();
            Console.ReadKey();
        }
    }
}
Explain the differences between overriding methods and abstract methods?
  1. The concept of abstract method is near similar to the concept of method overriding because in method overriding if a Parent class contains any virtual methods in it, then those methods can be reimplemented under the child class by using the override modifier.
  2. In a similar way, if a parent class contains any abstract methods in it, those abstract methods must be implemented under the child class by using the same override modifier.
  3. The main difference between method overriding and abstract method is in case of method overriding the child class reimplementing the method is optional but in case of the abstract method, the child class implementing the method is mandatory.
What is the need for abstract classes in application development?

The concepts of abstract methods and abstract classes is an extension to the inheritance wherein inheritance we have been discussing that with the help of a parent class we can provide property to the child class that can be consumed by the child classes which gives us reusability.

Along with the parent providing property to the children, the parent can also impose the restriction on the children with the help of abstract methods so that all the child classes have to full fill the restriction without failing.

PROGRAM: WAP where the abstract class MyClass has one abstract method which has got various implementations in sub-classes.
namespace AbstractDemo
{
    public abstract class MyClass
    {
        public abstract void calculate(double x);
    }
    class Sub1 : MyClass
    {
        public override void calculate(double x)
        {
            Console.WriteLine("SQUARE ROOT IS " + Math.Sqrt(x));
        }
    }
    public class Sub2 : MyClass
    {
        public override void calculate(double x)
        {
            Console.WriteLine("SQUARE is :" + (x * x));
        }
    }
    public class Sub3 : MyClass
    {
        public override void calculate(double x)
        {
            Console.WriteLine("CUBE is :" + (x * x * x));
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            Sub1 obj1 = new Sub1();
            Sub2 obj2 = new Sub2();
            Sub3 obj3 = new Sub3();
            obj1.calculate(9);
            obj2.calculate(9);
            obj3.calculate(9);
            Console.ReadKey();
        }
    }
}
OUTPUT:

Abstract class and abstract methods in C#

PROGRAM: WAP to calculate the electricity bills for commercial and domestic plans
namespace AbstractDemo
{
    public abstract class Plan
    {
        protected double rate;
        public abstract void getRate();
        public void calculation(int units)
        {
            Console.Write("BILL AMOUNT FOR " + units + " UNITS is: Rs.");
            Console.WriteLine(rate * units);
        }
    }

    class CommercialPlan : Plan
    {
        public override void getRate()
        {
            rate = 5.00;
        }
    }
    class DomesticlPlan : Plan
    {
        public override void getRate()
        {
            rate = 2.50;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Plan p;
            Console.WriteLine("COMMERCIAL CONNECTION");
            p = new CommercialPlan();
            p.getRate();
            p.calculation(250);
            Console.WriteLine("DOMESTIC CONNECTION");
            p = new DomesticlPlan();
            p.getRate();
            p.calculation(150);
            Console.ReadKey();
        }
    }
}
OUTPUT:

Abstract class and abstract methods in C#

PROGRAM: Program to show the use of abstract methods.
namespace AbstractDemo
{
    abstract class ClsEmployee
    {
        protected int EmpId, EAge;
        protected string EName, EAddress;
        public abstract void GetEmpData();
        public virtual void DisplayEmpData()
        {
            Console.WriteLine("Employee Id Is: " + this.EmpId);
            Console.WriteLine("Employee Name Is: " + this.EName);
            Console.WriteLine("Employee Address Is: " + EAddress);
            Console.WriteLine("Employee Age is: " + this.EAge);
        }
        public ClsEmployee()
        {
            Console.WriteLine("ABSTRACT CLASS CONSTRUCTOR");
        }
    }
    class ClsManager : ClsEmployee
    {
        double Bonus, CA;
        public override void GetEmpData()
        {
            Console.WriteLine("ENTER MANAGER DETAILS");
            Console.WriteLine("Enter the Manager Id: ");
            EmpId = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the Manager name: ");
            EName = Console.ReadLine();
            Console.WriteLine("Enter the manager Bonus: ");
            Bonus = double.Parse(Console.ReadLine());
            Console.WriteLine("Enter the Manager CA: ");
            CA = double.Parse(Console.ReadLine());
        }
        public override void DisplayEmpData()
        {
            Console.WriteLine("manager id is: " + EmpId);
            Console.WriteLine("manager name is: " + EName);
            Console.WriteLine("manager bonus is: " + Bonus);
            Console.WriteLine("Manager CA is: " + CA);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ClsManager cm = new ClsManager();
            cm.GetEmpData();
            cm.DisplayEmpData();
            Console.ReadKey();
        }
    }
}
OUTPUT:

Abstract class and abstract methods in C#

Please refer below MSDN article for more information about the abstract class and abstract methods in C#.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstractcsharp

SUMMARY:

In this article, I try to explain abstract class and abstract method in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *