What is Encapsulation?
Think of encapsulation like a capsule of medicine. A capsule keeps the medicine inside and controls how it is used.
In Java, encapsulation means hiding the inner details of an object and only showing what is necessary — just like how a capsule hides the bitter medicine and gives it in a safe way.
---
Real-Life Example: ATM Machine
Imagine an ATM machine. You insert your card, enter your PIN, and withdraw money. But you don’t know how the ATM internally processes your PIN or how it deducts money from your account. That’s encapsulation!
The inner details are hidden.
You only use the buttons and see the screen.
You can’t access or change the machine's internal parts.
In Java: How is Encapsulation Done?
Encapsulation in Java is done using:
1. Private variables: These are hidden from outside classes.
2. Public methods (getters and setters): These provide controlled access to the variables.
Code Example:
Let’s say we’re creating a Bank Account:
How it works:
You cannot directly access balance or account Holder from outside. They're hidden.
You must use methods like deposit(), withdraw(), and getBalance() to interact with the account.
These methods include rules, like not allowing you to withdraw more money than you have.
Why is Encapsulation Useful?
1. Security – Protects data from unauthorized access.
2. Control – Allows rules (e.g., no negative balance).
3. Simplicity – Users don’t need to know internal working.
4. Flexibility – You can change internal code without affecting users.
Comments
Post a Comment