Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that aims at binding the data (attributes) and the methods (functions) that operate on the data into a single unit known as a class.
Think of a company with different sections like finance, sales, etc. Each section has its own data and operations.
Finance section manages financial data.
Sales section manages sales data.
If someone from the finance section needs specific sales data, they can't access it directly. Instead, they have to request it through proper channels.
The key idea behind encapsulation is to hide the internal details of how the data is stored and processed, and provide controlled access to that data through well-defined methods.
This helps in achieving data protection, information hiding, and modularity in your codebase.
Encapsulation encourages the use of getter and setter methods to access and modify private data members.
Getters provide read access, while setters provide write access.
This allows you to validate and control the data being set or retrieved.
#include<iostream>
using namespace std;
class Solution
{
int a, b;
public:
void setData(int a, int b) //setter method with arguments
{
this->a = a;
this->b = b;
}
int getData() //getter method with return
{
return (a+b);
}
};
int main()
{
Solution obj;
obj.setData(2, 3);
cout<<obj.getData();
}
Encapsulation prevents direct access to the internal data of a class from outside the class.
Data members are usually marked as private to restrict direct modification.
By using access specifiers (private, protected, public), you control the visibility of members.
Encapsulation helps in creating modular code. Changes to the internal implementation of a class do not affect other parts of the code that use the class's public interface. This allows for easier maintenance and code updates.
With encapsulation, you can include validation checks and safeguards within the setter methods. This ensures that the data being set adheres to certain constraints and maintains data integrity.
Encapsulation promotes code reusability. Once a class is encapsulated, you can reuse it in various parts of your program without worrying about the internal details.