Encapsulation in Java
In this lesson: Hide data with private fields and public getters/setters in Java — benefits and examples with output. In Hindi & English.
What is Encapsulation?
Encapsulation means wrapping the data (variables) and the code (methods) that work on that data into a single unit — a class — and hiding the internal details from the outside world. In Java it is achieved by making fields private and giving controlled access through public getter and setter methods.
A medicine capsule wraps the medicine inside a shell — you can't touch the powder directly. Similarly, encapsulation wraps data inside a class and you access it only through methods.
How to Achieve Encapsulation
- Declare the class fields as
private. - Provide
publicgetter methods to read them. - Provide
publicsetter methods to change them (with validation).
class Account { private double balance; // hidden data public double getBalance() { // getter return balance; } public void deposit(double amt) { // controlled setter if (amt > 0) balance += amt; // validation! } } public class Main { public static void main(String[] a) { Account ac = new Account(); ac.deposit(500); System.out.println(ac.getBalance()); } }
500.0
Benefits of Encapsulation
| Benefit | Why it matters |
|---|---|
| Data hiding | Outside code can't directly change balance to an invalid value. |
| Control | The setter can validate input (no negative deposit). |
| Flexibility | You can change the internal code later without breaking other classes. |
| Read-only / write-only | Provide only a getter (read-only) or only a setter (write-only) as needed. |
Making fields public defeats encapsulation — anyone can then set balance = -9999. Always keep fields private.
Summary
- Encapsulation = data + methods in one class, with internal details hidden.
- Achieved by
privatefields +publicgetters/setters. - Gives data hiding, validation, flexibility and controlled access.
