OOP · The Four Pillars
Encapsulation
Imagine you are developing a Banking Application.
Problem Statement
Imagine you are developing a Banking Application. Every customer has a bank account. Each account stores important information such as:
- Account Number
- Account Holder Name
- Balance
But since the variables are public, anyone can modify them.

What is the problem?
- A bank balance should never become negative.
- Any developer can change important data.
- Invalid values can break the application.
- Business rules are ignored.
This is a serious security issue.
Real-World Impact
Imagine this happens in an online banking system. A developer accidentally writes:
The program compiles successfully. Now the customer sees a negative balance that should never exist. A single mistake can affect thousands of users. Large companies cannot allow this.


Why Does This Happen?
The variables are public. Public variables can be accessed and modified from anywhere in the program. There is no control over who changes the data or what values are assigned. We need a way to protect important information.
Solution – Encapsulation Instead of allowing direct access to variables, we make them private. Only the class itself can access private variables. Other classes must use special methods to read or update the data. This concept is called Encapsulation. What is Encapsulation?
Encapsulation is the process of combining data and the methods that operate on that data into a single class while restricting direct access to the data. Instead of exposing variables, the class provides controlled access through methods.

How Encapsulation Protects Data
Make Variables Private Declare important variables as private to prevent direct access from outside the class.
Read Data Using a Getter- Provide a getter method to allow controlled access to private variables.
Update Data Using a Setter Provide a setter method to modify private variables in a controlled manner.
Add Validation Validate the input inside the setter before updating the variable to ensure only valid data is stored.

Hide fields behind private and expose controlled access so invariants can't be broken.
public class BankAccount {
private double balance; // hidden — no outside code can corrupt it
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Must be positive");
balance += amount;
}
public boolean withdraw(double amount) {
if (amount > balance) return false; // guard keeps state valid
balance -= amount;
return true;
}
public double getBalance() { return balance; } // read-only access
}