Abstract Class in c#

Introduction

An Abstract class is a class that cannot be instantiated. An Abstract keyword enables you to create classes and class members that are incomplete and must be implemented in derived class.
 
An abstract class can contain abstract methods, non abstract methods, fields, constant, properties, constructor and destructor.

The purpose of abstract class is to provide a common definition of a base class that multiple derived class can use. Class can be declared as Abstract by putting Abstract before the class definition.

Syntax
 
Abstract class classname
{
// code comes here
}
 
Method can be declared as abstract by adding the keyword abstract before the return type of method.

Imp:
 Abstract methods have no implementation, method definition is followed by semicolon instead of a method block. An Abstract method is implemented using override keyword.

Derive class of abstract class must implement all abstract methods otherwise it will generate an error.
 
Example

An example of abstract class:
 

using System;

namespace abstractclass

{

    public abstract class a

    {

        public abstract void m();

    }

    class Program : a

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Hello In main method");

            Console.ReadKey();

        }

    }

}
 

generate an error " abstractclass.Program does not implement inherited abstract member abstractclass.a.m()".

Correct Program


using
 System;
namespace abstractclass
{
    
public abstract class a
    {
        
public abstract void m();
    }
    
class Program : a
    {
        
public override void m()
        {
            
Console.WriteLine("abstract class method");
        }
        
static void Main(string[] args)
        {
            
Program p = new Program();
            p.m();
            
Console.WriteLine("Hello In main method");
            
Console.ReadKey();
        }
    }
}

Output

Image1.jpg

Important points regarding Abstract class and Abstract Method
  • Abstract method cannot be declare static and if do so it will generate an error ( reason: because static method cannot be marked as override, abstract or virtual).
  • Can not use sealed keyword with Abstract method.
  • Abstract class cannot be made private.
Ebook Download
View all
Learn
View all