abstract classes in C#

Introduction

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don�t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An example of an abstract class declaration is:
abstract class absClass
{
}
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An example of an abstract method:
abstract class absClass
{
  public abstract void abstractMethod();
}
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members. For example:
abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}
A sample program that explains abstract classes:
using System;

namespace abstractSample
{
      //Creating an Abstract Class

      abstract class absClass
      {
            //A Non abstract method

            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            //An abstract method, to be

            //overridden in derived class

            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }

      //A Child Class of absClass

      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an

               //instance of the derived class


               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }

            //using override keyword,

            //implementing the abstract method

            //MultiplyTwoNumbers

            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.

Example

//Abstract Class1

abstract class absClass1
{
    public abstract int AddTwoNumbers(int Num1, int Num2);
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//Abstract Class2

abstract class absClass2:absClass1
{
    //Implementing AddTwoNumbers

    public override int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1+Num2;
    }
}

//Derived class from absClass2

class absDerived:absClass2
{
    //Implementing MultiplyTwoNumbers

    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1*Num2;
    }
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.

Abstract properties

Following is an example of implementing abstract properties in a class.
//Abstract Class with abstract properties

abstract class absClass
{
    protected int myNumber;
    public abstract int numbers
    {
        get;
        set;
    }
}

class absDerived:absClass
{
    //Implementing abstract properties

    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}
In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the derived class absDerived.

Important rules applied to abstract classes

An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//Incorrect

abstract sealed class absClass
{
}
Declaration of abstract methods are only allowed in abstract classes.
An abstract method cannot be private.
//Incorrect

private abstract int MultiplyTwoNumbers();
The access modifier of the abstract method should be 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.
An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
//Incorrect

public abstract virtual int MultiplyTwoNumbers();
An abstract member cannot be static.
//Incorrect

publpublic abstract static int MultiplyTwoNumbers();

Abstract class vs. Interface

An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
  //All methods are automaticall abstract

  int AddNumbers(int Num1, int Num2);
  int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both depending on your needs.

16 comments:

de said...

Great explanation on abstract class.


Prathap
Dot net training in chennai

Information said...

Thank Q prathap Kumar

Anonymous said...

It was really a wonderful article and I was really impressed by reading this blog. We are giving all software Course Online Training. The HTML5 Training in Chennai is one of the reputed Training institute in Chennai. They give professional and real time training for all students.

Subash said...
This comment has been removed by the author.
priya said...

All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.
Data Science course in rajaji nagar
Data Science with Python course in chenni
Data Science course in electronic city
Data Science course in USA
Data science course in pune | Data Science Training institute in Pune
Data science course in bangalore

Mounika said...

Write more; that’s all I have to say. It seems as though you relied on the video to make your point. You know what you’re talking about, why waste your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?

python training in chennai
python course in chennai
python training in bangalore

Anjali M said...
This comment has been removed by the author.
Harini Priya said...
This comment has been removed by the author.
Softgen Infotech said...

Such a great information for blogger i am a professional blogger thanks…

Join Cloud Computing Training in Bangalore at Softgen Infotech. Learn from Certified Professionals with 10+ Years of experience in Cloud Computing. Get 100% Placement Assistance. Placements in MNC after successful course completion.

EXCELR said...

The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.data science course in Hyderabad

jeni said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.

hardware and networking training in chennai

hardware and networking training in velachery

xamarin training in chennai

xamarin training in velachery

ios training in chennai

ios training in velachery

iot training in chennai

iot training in velachery

Jayalakshmi said...

It's a very awesome article! Thanks a lot for sharing information.
sap training in chennai

sap training in tambaram

azure training in chennai

azure training in tambaram

cyber security course in chennai

cyber security course in tambaram

ethical hacking course in chennai

ethical hacking course in tambaram

deiva said...

Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
web designing training in chennai

web designing training in omr

digital marketing training in chennai

digital marketing training in omr

rpa training in chennai

rpa training in omr

tally training in chennai

tally training in omr

shiny said...


It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time.




oracle training in chennai

oracle training in annanagar

oracle dba training in chennai

oracle dba training in annanagar

ccna training in chennai

ccna training in annanagar

seo training in chennai

seo training in annanagar

praveen said...

First i got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks.
hardware and networking training in chennai

hardware and networking training in porur

xamarin training in chennai

xamarin training in porur

ios training in chennai

ios training in porur

iot training in chennai

iot training in porur

data scientist course said...

Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
data scientist training and placement in hyderabad

Post a Comment