Encapsulation in Object-Oriented Programming
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It is the practice of restricting direct access to certain details of an object and only allowing controlled access through public methods. This enhances security, data integrity, and maintainability.
Why Use Encapsulation?
- Data Protection: Prevents unauthorized access to object properties.
- Improved Maintainability: Reduces dependencies between different parts of the code.
- Better Code Organization: Encourages modular and structured programming.
How Encapsulation Works
Encapsulation is achieved using access modifiers such as private
, protected
, and public
to control the visibility of class members.
Example:
class BankAccount
{
private double balance; // Private field, cannot be accessed directly
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
public void Deposit(double amount)
{
if (amount > 0)
{
balance += amount;
Console.WriteLine($"Deposited: {amount}");
}
}
public double GetBalance()
{
return balance; // Controlled access to private field
}
}
var account = new BankAccount(1000);
account.Deposit(500);
Console.WriteLine($"Current Balance: {account.GetBalance()}");
Key Takeaways:
- The
balance
field is private and cannot be accessed directly.
- Public methods (
Deposit
and GetBalance
) are used to interact with the object's data safely.
Conclusion
Encapsulation helps enforce data integrity by controlling access to object properties. It ensures that only valid operations are performed on an object, making the system more robust and secure.
In the next articles, we will explore other Object-Oriented Programming principles such as Inheritance and Abstraction using a consistent example structure.