Encapsulation Basics
Data hiding and bundling
Interview Relevant: Core OOP principle
4 min read
Encapsulation in Java
Encapsulation is the practice of wrapping data (variables) and methods together and restricting direct access to the data.
Key Idea: Protect internal state using private access and expose behavior via methods.
Code Examples
Data hiding using private variables
java
1
2class BankAccount {
3 private double balance; // hidden data
4
5 public void deposit(double amount) {
6 if (amount > 0) {
7 balance += amount;
8 }
9 }
10
11 public double getBalance() {
12 return balance;
13 }
14}
15
16BankAccount acc = new BankAccount();
17acc.deposit(1000);
18// acc.balance = 5000; // ā Not allowed
19System.out.println(acc.getBalance());
20 Use Cases
- Protecting object state
- Preventing invalid data modification
- API stability
Common Mistakes to Avoid
- Using public fields
- Exposing internal state directly