Abstraction in C#

Abstraction is an important feature of any object-oriented programming language. Abstraction involves extracting only the relevant information. Abstraction doesn't mean that information is unavailable. In other words all the information exists but only the relevant information is provided to the user.

Abstract class
 
C# enables us to create abstract classes that are used to provide partial class implementation of an interface. We can complete an implementation using the derived classes. Abstract classes contain abstract methods, which can be implemented by using abstract classes and virtual functions.
 
There are certain rules governing the use of abstract class. These are:
 
  1. Cannot create an instance of an abstract class.
  2. Cannot declare an abstract method outside an abstract class.
  3. Cannot be declared sealed. (Sealed classes can never be inherited.)
The syntax to declare a class Abstract is:
 
               abstract class classname
               
                {
                          ..........
                 }

Abstract methods
 
Abstract methods are the methods without any body. The implementation of an abstract method is done by the derived class. When a derived class inherits the abstract method from the abstract class, it must override the abstract methods.
 
The syntax for using the abstract method is:
 
[access-modifier] abstract  <return-type> <method-name([parameters])>

The following code illustrates the use of an Abstract method:
 
using System;
namespace abstractclass
{
   
       abstract class baseclass
       {
          publicabstract void m1();
       }
          class derived:baseclass
    {
     public  override  void  m1()
        {
            Console.WriteLine("success");
        }
    }
    public class implement
    {
 
        static voidMain(string[] args)
        {
            derived ob =new derived();
            ob.m1();
            Console.Read();
        }
     }
}

In the above code example, the abstract method is declared by adding the abstract modifier to the method. Abstract method m1() is declared in the abstract class named "baseclass". The abstract method is inherited in a "derived" class. Abstract methods cannot contain a method body.

Up Next
    Ebook Download
    View all
    Learn
    View all