Categories
C# / .NET Program

C# Abstract Keyword

  • Abstract is a Keyword & Access Modifier similar to public, private, protected.
  • As name implies Abstract keyword is an template like modifier.
  • It is an incomplete method, class, properties, indexes and events. Which should be completed in derived class.
  • Abstract class are always base class.
  • The members in the abstract class to be implement by the derived class of the respective abstract class.
  • You have to use override keyword in derived class to define the incomplete methods.

Abstract Class & Method

Abstract Class can contain only abstract method.

Step 1. Code for Abstract Class & Method Declaration:

abstract class abstractclass
    {
        abstract void absMethod();
    }

Step 2. Defining the abstract method in derived class, use override keyword in method

class derivedClass: abstractclass
    {
        string msg = "";

        public override void absMethod()
        {
            Console.WriteLine(msg);
        }
    }

 Step 3. In the main method, you can call derived class which implement the Abstract class.

using System;

namespace keywords
{
    abstract class abstractclass
    {
        abstract public void absMethod();
    }

    class derivedClass: abstractclass
    {
        string msg = "Abstract Class is invoked";

        public override void absMethod()
        {
            Console.WriteLine(msg);
            Console.ReadKey();
        }

        public static void Main()
        {
            derivedClass dc = new derivedClass();
            dc.absMethod();
        }
    }

}

 

Output:

Abstract Class is invoked


Features Abstract Class:

  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed (C# Reference) modifier because the two modifers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Leave a Reply

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