What is Encapsulation?
Encapsulation is one of the key principles of Object-Oriented Programming (OOP). It refers to the practice of wrapping data (variables) and methods (functions) into a single unit and restricting direct access to some of an object's components.
Encapsulation = Data Hiding + Controlled Access
Why Use Encapsulation?
- ✔ Protects data from accidental modification
- ✔ Controls how data is accessed
- ✔ Improves code security and maintainability
- ✔ Keeps implementation details hidden
Real-Life Example
Think of a medicine capsule. You cannot directly see or touch the powder inside; you just use the capsule. Similarly, encapsulation hides internal data and allows controlled interaction.
C# Example of Encapsulation
class BankAccount
{
private double balance; // hidden data
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
In this example:
privatekeyword hides the variablebalance.- Access is controlled using methods like
Deposit()andGetBalance().
Key Points to Remember
- Encapsulation hides internal data.
- Uses access modifiers like
private,public, andprotected. - Improves code security, reliability, and flexibility.
No comments:
Post a Comment