Abstract class in c#

Abstract class :

In C#, you can have a single base class and multiple derived classes. If you do not want that any class can create an object of the base class, you can make the base class abstract. The abstract keyword in a class indicates that the class cannot be instantiated. You can create the instance of its derived class. The following code snippet shows how to create an abstract class :

Example of abstract class

abstract class BaseClass
{
  //Data Members and Member Functions
}
class DerivedClass:BaseClass
{
  //Data Members and Member Functions
}
void main()
{
    BaseClass bc;  //Can't be instantiated
    Derived dc;  //Can be instantiated
}

In the preceding code snippet, we cannot instantiate the BaseClass class because we have declared it as abstract.


Some characteristics of an abstract class are as follows :

  • Restricts instantiation, implying that you cannot create an object of an abstract class
  • Allows you to define abstract as well as non-abstract members in it.
  • Requires at least one abstract method in it.
  • Restricts the use of sealed keywords in it.
  • Possesses public access specifier; therefore, it can be used anywhere in a program

Abstract methods :

An abstract method is similar to a virtual method which does not provide any implementation; therefore, an abstract method does not have a method body. It can be declared by using the abstract keyword. The following code snippet shows how to create an abstract method :

public abstract void Area(int Length,int Breadth);

Some characteristics of an abstract method are as follows :

  • Restricts implementation in an abstract class
  • Allows implementation in a non-abstract derived class
  • Requires declaration in an abstract class only
  • Restricts declaration with static and virtual keywords
  • Allows you to override a virtual method

Example of abstract method

public abstract class Shape
{
  public abstract void Area(int Length, int Breadth)
  {
        //Method Area() can't be implemented at this place.</span>
  }
}
public abstract class BasicShape: Shape
{
}
public class Rectangle: BasicShape
{
  public override void Area(int Length, int Breadth)
  {
        <span>//Method Area() can be implemented at this place</span>
  }
}


Write a comment


Name Email Message