Encapsulation
Encapsulation
Encapsulation is the process of bundling data and the methods that operate on that data inside a class and restricting direct access to the internal data.
In simple words:
Encapsulation = Data hiding + Controlled access
Real-Life Example: Bank Account
Think about a bank account. You can deposit money, withdraw money, and check your balance, but you cannot directly change the balance to any value you want.
For example, you should not be able to directly set your balance to ₹1,00,00,000. Instead, the bank provides controlled operations such as deposit(), withdraw(), and getBalance(). The actual balance is kept private and can only be accessed or modified through these valid operations.
How Encapsulation Works in Java
There are a few important concepts involved:
| Concept | Purpose |
|---|---|
private | Hides the internal data |
public methods | Provide controlled access |
| Getter | Allows reading data |
| Setter | Allows modifying data |
| Validation | Prevents invalid data |
Java Example
class BankAccount {private double balance;public void deposit(double amount) {if (amount > 0) {balance += amount;}}public void withdraw(double amount) {if (amount > 0 && amount <= balance) {balance -= amount;}}public double getBalance() {return balance;}}
Using the Class
BankAccount account = new BankAccount();account.deposit(1000);account.withdraw(300);System.out.println(account.getBalance()); // 700
Why is balance Private?
If balance were public:
class BankAccount {public double balance;}BankAccount account = new BankAccount();account.balance = -5000; // Invalid value
Anyone could directly modify the balance.
By making it private:
class BankAccount {private double balance;}
the outside code cannot directly access or modify it. Instead, it must go through methods where we can apply rules and validation.
Encapsulation vs Data Hiding
These terms are related but not exactly the same.
| Encapsulation | Data Hiding |
|---|---|
| Bundles data and methods together | Restricts access to internal data |
| Achieved through classes | Commonly achieved using private |
| Broader concept | Part of encapsulation |
Key Benefits
| Benefit | Explanation |
|---|---|
| Data Protection | Prevents direct modification |
| Validation | Allows checking data before changing it |
| Control | Decides how data can be accessed |
| Maintainability | Internal implementation can change without affecting users |
| Security | Hides sensitive internal details |
Interview Definition
Encapsulation is an OOP principle that bundles data and the methods that operate on that data within a class while restricting direct access to the internal state.
Remember
Private data + controlled public methods = Encapsulation