5.
Encapsulation (Object-Oriented Programming)
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP).
It refers to the bundling of data (variables) and the methods (functions) that operate on that data
into a single unit, or class, and restricting direct access to some of the object’s components.
The main idea is "hide the internal state of an object and require all interaction to be
performed through an object's methods."
Benefits of Encapsulation:
Data Hiding: Prevents external code from directly accessing internal data, reducing the
chance of accidental corruption.
Modularity: Changes in the internal implementation of a class do not affect code that
uses the class.
Code Maintainability: Easier to debug and manage.
Security: Sensitive data can only be accessed through controlled, defined methods.
Example in C#:
csharp
CopyEdit
public class BankAccount {
private double balance;
public void Deposit(double amount) {
if (amount > 0) balance += amount;
}
public double GetBalance() {
return balance;
}
}
Here, balance is private and can only be changed using the Deposit method. This protects it
from being arbitrarily altered, which is key in secure and reliable software.
Encapsulation is used in building real-world systems like banking apps, ticketing systems,
inventory tracking, etc., where data integrity is critical.
Let me know if you want diagrams, visuals, or real-world examples added to any of these!