Abstraction in object-oriented programming is a way to hide the details and only displaying the relevant information to the users. It is a technique through which we can separate the interface with the implementation details.
Abstraction and encapsulation are the related feature in C#. Abstraction is used to hide the implementation detail while encapsulation is a way to achieve the desired level of abstraction.
Take a real-life example:
Suppose you are switching the channel with your TV remote control. You click the button to switch to the desired channel on a TV but how the implementation of switching channel with a click of a button is unknown to you, that is an abstraction. It hides the detail of how the work is done inside the remote control. The users are only familiar with the button and how to operate with the button.
In C#, abstraction can be achieved in two ways.
- Abstract class.
- Interfaces.
Let us first see an abstract method.
Abstract Method
Abstraction and interface both have abstract methods. The method that has no body is called the abstract method. An abstract method is also declared with an abstract keyword and ends with a semicolon(;) instead of curly braces({}).
Syntax of abstract method:
public abstract void methodName();
C# Abstract Class
In C#, the class declared with an abstract keyword is called an abstract class. An abstract class may or may not have abstract methods.
An object of abstract class cannot be created in C#, to access this class, it must be inherited from another class.
Syntax of an abstract class:
abstract class ClassName {
. . . . .
}
Let us go through an example of an abstract class in C#
Example: C# program for an abstract method
In the example below, we create an abstract class with an abstract method that is inherited by another class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | using System; //abstraction class public abstract class Animal { //abstraction method public abstract void sound(); } public class Dog: Animal { //override abstraction method public override void sound() { Console.WriteLine("Dog barks"); } } public class Cat: Animal { //override abstraction method public override void sound() { Console.WriteLine("Cat Meows"); } } public class AbstractMain { public static void Main() { Animal dg = new Dog(); Animal ct = new Cat(); dg.sound(); ct.sound(); } } |
Output:
Dog barks
Cat Meows
Advantage of data abstraction
- It also avoids code duplication increases the reusability of the code.
- Since the abstraction separates the interface and implementation, the internal changes can be easily made without affecting the user-level code.
- The abstracting of the data itself increases the security as no user can access the internal hidden mechanism.