Encapsulation in Java
What is Encapsulation?
Encapsulation is the process of wrapping data (variables) and code (methods) together as a single unit — typically inside a class.
It’s also called "data hiding" because it restricts direct access to class variables.
Key Features of Encapsulation
- Make variables private
- Provide public getter and setter methods to access/change them
- Control what data can be seen or modified
Example of Encapsulation:
class BankAccount {
private double balance; // private variable (hidden)
// Getter
public double getBalance() {
return balance;
}
// Setter
public void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
System.out.println("Invalid amount!");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.setBalance(5000.75); // modify using setter
System.out.println(acc.getBalance()); // access using getter
}
}
Output:
5000.75
Why Use Encapsulation?
Benefit | Description |
---|---|
Data Hiding | Prevents direct access to sensitive fields |
Controlled Access | Only expose what is needed |
Security | Protects object’s internal state |
Code Flexibility | Easy to update or refactor |
Cleaner API | Users interact via methods, not internal variables |
Real Life Analogy
-
Imagine a coffee machine:
- You press a button to make coffee.
- You can’t see or access internal parts like wiring or boiler.
- That’s encapsulation — the complexity is hidden, and only the interface is exposed.
Summary
Concept | Description |
---|---|
What | Wrapping data and methods inside a class |
How | Use private + getters & setters |
Benefit | Security, clean code, control, and maintainability |