Abstraction vs Encapsulation in C#: Difference between abstraction and encapsulation

difference between abstraction and encapsulation
difference between abstraction and encapsulation

In C#, the key difference between abstraction and encapsulation is that encapsulation wraps data and methods into a single unit called class, whereas abstraction hides implementation details and just shows users the functionality.

What is the difference between abstraction and encapsulation in C# programming?

In C#abstraction focuses on the design level. It simplifies complex concepts by highlighting essential features while hiding unnecessary details. It defines what an object should do without exposing how it achieves its purpose. 

Abstraction Example: Think of the outer layout of a Phone – The display screen is an important feature that represents the necessary functionality without exposing the internal mechanics.

On the other hand, encapsulation operates at the implementation level. It shields internal details from external users. It wraps data and methods into a single unit (class), ensuring that clients interact with public properties rather than directly accessing private data. 

Encapsulation Example: Imagine the inner implementation details of a Phone – the complex connections between display screens using circuits. Encapsulation shields these details from external users.

Definition of Abstraction in C#

Abstraction is the technique of exposing only the essential details while hiding the rest. In simple words, data abstraction is defined in C# as the process of reducing an object to its core and exposing only the relevant details of the object to the users.

Abstraction is the process of working with ideas rather than putting them into action.
The implementation complexities are hidden from the users in abstraction.

How to Achieve Abstraction in C#?

  • In C#, Abstract classes and interfaces can be used to achieve Data Abstraction.
    Complete abstraction is possible with interfaces that allow you to entirely encapsulate the implementation.
  • Abstract classes allow partial or complete abstraction because they might have concrete methods with implementation, resulting in partial abstraction.

Definition of Encapsulation in C#

The wrapping up of code and data into a single unit (class) is referred to as encapsulation. Encapsulation can also be thought of as a shield to protect the data from being accessible by code outside of the shield.

Key points about encapsulation

Encapsulation in C# is a fundamental object-oriented programming (OOP) concept that refers to hiding an object’s implementation details from other parts of the program. It involves bundling the data (fields, properties) and behavior (methods) that operate on that data within a single unit called a class.

The class exposes a set of well-defined public interfaces (methods, properties, events) that other parts of the program can use to interact with the object while keeping the implementation details hidden. It provides several benefits, including:

  • Increased security: Encapsulation helps prevent unauthorized access to an object’s internal state by restricting direct access to its fields and properties.
  • Improved maintainability: Encapsulating the implementation details of an object makes it easier to modify or update the object’s behavior without affecting other parts of the program.
  • Increased code reusability: Encapsulation promotes modular design by treating objects as black boxes with well-defined interfaces that can be reused in different contexts without knowing the implementation details.

In C#, encapsulation is typically achieved using access modifiers such as private, public, protected, and internal to control the visibility of the members of a class. By default, the access level of a member is private, meaning that it can only be accessed within the same class. On the other hand, Public members can be accessed from any part of the program.

Read my previous article to learn more about Encapsulation in C#.

How to Achieve encapsulation in C#?

In C#, encapsulation can be performed by:

  • Declaring class variables as private.
  • Providing a public method or a getter and setter property that can be used to modify and read the values of private variables.

Encapsulation refers to a situation in which a class’s variables or data are hidden from other classes and can only be accessed through member functions/properties of the class in which they are specified.

Let’s take a look at the code to see how encapsulation is implemented:

abstraction vs encapsulation
encapsulation in C#

As you can see in the above code, I have created a class Employee which has private variable names firstName and lastName. Then, I created a public property fullName to get the value from the private variables. Because private fields cannot be accessed outside of the class, any class wishing to obtain the employee name (private fields value) must use this public property.

This allows us to quickly obtain the employee`s full name without having to worry about how the Employee class handles first and last names internally.

Advantages of Encapsulation

The most significant benefit of encapsulation is data security. The following are some of the advantages of encapsulation:

  • Encapsulation protects an object against unwanted client access.
  • Encapsulation allows you to access a level without revealing the underlying technical details.
  • Data Hiding can be accomplished via encapsulation: A user will have no clue how the class is implemented internally. Even the user will have no idea how the class stores values in variables. Users will only be aware that the values are passed to a setter method or constructor, and that variables are initialized with that value.
  • By keeping data private and giving the public well-defined service methods, the object’s purpose becomes clear to other objects, which increases its usability.

Refer this link to learn more about the Encapsulation in C#

Difference between Abstraction and Encapsulation in C#

AbstractionEncapsulation
1. Abstraction is a technique for hiding unnecessary information.Encapsulation, on the other hand, is a way of hiding data in a single unit called Class as well as a method of protecting information from the outside.
2. Abstract classes and interfaces can be used to implement abstraction.Encapsulation, on the other hand, can be implemented utilizing access modifiers such as private, protected, and public.
3. Abstraction solves a problem at the design level.whereas Encapsulation solves an issue at the implementation level.
4. Abstraction is used to hide something, but to a greater extent (class, interface). Clients who use an abstract class (or interface) are only interested in knowing what it can do, not what it was.Encapsulation hides private variables or implementations in a class that are frequently modified to prevent outsiders from accessing them directly. We must use the getter and setter methods of a property to access them.
5. Abstraction emphasizes what should be done.whereas encapsulation emphasizes how it should be done.
6. The class that implements the abstraction can be used as a parent class, with the child class inheriting its functionality, increasing reusability and reducing duplication.Encapsulation allows the programmer to have more control over the data’s accessibility and transparency.
Abstraction vs Encapsulation in C#

Abstraction example

The following is a code snippet for data abstraction:

using System;
namespace AbstractionExample
{
    /* C# program written to calculate the area
      of a Circle and square using the concept of
      data abstraction */

    // Abstarct class
    abstract class Shape
    {
        // Abstract method
        public abstract double area();
    }

    // Child class( Circle) inheriting
   // the parent (Shape) class.
    class Circle : Shape
    {
        // private data member
        private double radius;

        // Constructor
        public Circle(double radius)
        {
            this.radius = radius;
        }

        // overriding of the abstract method using the override keyword.
        public override double area()
        {
            return (3.14 * radius * radius);
        }
    }
    class Square : Shape
    {
        private double side;
        public Square(double side)
        {
            this.side = side;
        }    
        public override double area()
        {
            return (side * side);
        }
    }
   
    class Program
    {
        static void Main(string[] args)
        {
            // Creating reference of Parent (Shape) class
            // which refer to child (Circle & Square) classes instance.
            Shape shape = new Circle(5.0);
            Console.WriteLine($"Area of Circle = {shape.area()}");
                  shape = new Square(5.5);
            Console.WriteLine($"Area of Square = {shape.area()}");
            Console.ReadLine();

            //Output:
            //Area of Circle = 78.5
            //Area of Square = 30.25
        }
    }
}

The Base class only exposes the method definition, input parameters, and return type of the abstract method. However, it does not expose the method`s implementation details, such as how it is implemented differently in different child classes; this is referred to as abstraction.

FAQs:

Q: Is there a difference between abstraction and abstract class?

Ans: Many people are puzzled by the terms abstraction and abstract class, Are they related?
Well, an abstract class differs from abstraction in that it is created with the goal of being implemented in a child class or subclass. Abstraction simply hides the data and reveals only the essential data by using access specifiers like public, protected, and private.

Q: How do you achieve abstraction in C#?

Ans: In C#, abstraction can be achieved by abstract classes and interfaces.

Q: What is an abstraction, and how can you describe it with an example?

Ans: In simple terms, abstraction hides unnecessary information and only shows the relevant attributes of an object.

For example, when driving a car, we are just concerned with driving the car, such as starting/stopping the car, accelerating/braking, and so on. We are unconcerned about the internal operation of the start/stop mechanism or the accelerate/brake process. We are simply uninterested in such technicalities.

Q: What is the main difference between encapsulation and abstraction in C#?

Encapsulation in C# is an OOP concept that encapsulates data and methods in a single unit known as class. On the other hand, abstraction in C# is an OOP concept that hides the implementation details and exposes only the functionality to the user.

Q: How are Abstraction and Encapsulation related?

They go hand in hand. Abstraction simplifies what an object does, while encapsulation ensures that its implementation details remain hidden. Together, they make code more organized and maintainable.

Conclusion

In this post, we have gone through the relevance of the OOPs concept and learned what abstraction and encapsulation mean. We went over several abstraction and encapsulation examples. We also discussed the advantages of abstraction and encapsulation. Finally, we looked at the difference between abstraction and encapsulation.

Thank you for reading the blog; if you enjoyed it, please like, comment, and share it with others. 

References: C# | Abstraction

Articles to Check Out:

Shekh Ali
4.8 4 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments