Article

Abstraction


Abstraction

To achieve security - hide certain details and only show the important details of an object. The abstract keyword is used for classes and methods.

Abstract class

abstract class is an incomplete class or special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions.

Abstract method

A method which is declared abstract has no “body” and declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it.

An abstract class can have both abstract and regular methods.

Example

Consider a real-life scenario of withdrawing money from ATM. The user only knows that in ATM machine first enter ATM card, then enter the pin code of ATM card, and then enter the amount which he/she wants to withdraw and at last, he/she gets their money. The user does not know about the inner mechanism of the ATM or the implementation of withdrawing money etc. The user just simply knows how to operate the ATM machine, this is called abstraction.

using System;

namespace MyApplication
{
  // Abstract class
  abstract class ATM 
  {
    // Abstract method (does not have a body)
    public abstract void balanceShow();
    // Regular method
    public void changePassword()
    {
      Console.WriteLine("i want to change my password");
    }
  }
  
  // Derived class (inherit from ATM)
  class withdrawMoney : ATM 
  {
    public override void balanceShow()
    {
      // The body of balanceShow () is provided here
      Console.WriteLine("The money show: xyz Rs.");
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
    withdrawMoney mymoney = new withdrawMoney ();  // Create a withdrawMoney object
      mymoney.balanceShow();
      mymoney.changePassword();
    }
  }
}

Advantage

  • It reduces the complexity of viewing things.
  • Avoids code duplication and increases reusability.
  • Helps to increase the security of an application or program as only important details are provided to the user.

In C# abstraction is achieved with the help of Abstract classes.

Note: Abstraction can also be achieved with Interfaces.