What is Encapsulation?
Encapsulation is the process of putting something into a capsule. In programming, Encapsulation represents the grouping of logically related data and operations into blocks called classes. In real life context, a company can encapsulate its stakeholders into the following groups according to their functionalities: Employee, Product, Customer, Supplier, Share holder etc.
Encapsulation serves following purposes:
- Logically related data and operations are grouped together in the form of an entity to simplify their management.
- It provides a mechanism of access control i.e. data hiding.
What is Data Hiding?
The process of hiding the data of an entity from other entities is called Data Hiding . It is made possible because of Encapsulation. The purpose of Data Hiding is to prevent corruption of data by other entities.
In real life context, All the things that we have in our houses can be thought of as our data. Different type of people such as unknown visitors, friends and relatives come to our house. We don’t want to show each and every item of our house to each person hence we apply different access rules to them.
Encapsulation isn’t Data Hiding.
Encapsulation is the means (saadhan) and Data Hiding is the end (lakshaya) . Because of the one the other is possible. When we create a group we encapsulate, and when we apply different access rule on its members we do data hiding. We can’t hide data without groups but we can create groups without data hiding. These groups will act like public places such as roads, parks etc where all the persons have same access.
What is Abstraction?
Abstraction is the process of hiding the internal working of a process from its end user. In the context of programming, separating the signature of a method from its definition is called abstraction. When a programmer wants to perform a task, he looks for a method which can do it for him. If such a method is found, the programmer invokes it without bothering about its internal working.
Relation among Encapsulation, Data Hiding and Abstraction?
To understand the relation and differences among Encapsulation, Data Hiding and Abstraction, we need to understand their users i.e for whom these concepts are designed. As a programmer, either we write our own code or use the code of others (libraries, frameworks, and classes & methods of other team members) i.e. we play two roles: Creator & User.
When we play the role of the creator, we classify entities according to their functionality to simplify their management i.e we encapsulate. As part of the encapsulation, we also apply access control i.e. Data Hiding. We decide, which data and operations of an entity are to be exposed to other entities. When we play the role of the user, we simply search the classes & methods of others which can do the intended task. We are not interested in who wrote them, or what data and logic they use.