what is an Abstract class in c#


share this interview article on:

What is Abstract Class ?

An Abstract class is a special class which cannot be instantiated. We can use an Abstract class as a Base Class.

 

Abstract Class Declaration:

we can declare Abstract class with keyword   abstract  which is given below.

abstract class absClass
{
}

no object of this class can be instantiated ( i.e. object cannot be created using the new keyword ), but can make derivations of this.

absClass a = new absClass();

It will give Compiler Error: Cannot create an instance of the abstract class.

 

Abstract class can contain both Abstract and Non-Abstract members.

 

Abstract Methods:

Abstract members are simply declared and are defined in the classes deriving the Abstract class.

Abstract members do not have any implementation in the abstract class

Abstract members are defined by using the override keyword in derived class.

 

Abstract method Declaration:

abstract class absClass
{
  public abstract void abstractMethod();
}

 

NonAbstract Method:

Non-Abstract members are defined within the Abstract class.

Non-Abstract members can be accessed within the derived classes only if marked public or protected.

 

NonAbstract method Declaration:

abstract class absClass
{
    public void NonAbstractMethod()
    {
        Console.WriteLine("NonAbstract Method");
    }
}

see the below sample which define Abstract class with abstract member and nonabstract member.

using System;

namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {

            //An abstract method, to overridden in derived class

           public abstract int MultiplyNumbers(int Num1, int Num2);

            //A Non abstract method
            public int AddNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }

            
      }

      //A Child Class of absClass
      class absDerived:absClass
      {
          
            static void Main(string[] args)
            {
               //You can create an instance of the derived class

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

            //using override keyword,implementing the abstract method
            //MultiplyNumbers
            public override int MultiplyNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

In the above sample example, you can see that the abstract class absClass contains two methods AddNumbers and MultiplyNumbers

AddNumbers is a non-abstract method which contains implementation and MultiplyNumbers is an abstract method that does not contain implementation.



Related Interview Questions

ADS

Tags:

c# abstract class