OOP

Encapsulation

Encapsulation

Encapsulation is the process of bundling data and the methods that operate on that data inside a class and restricting direct access to the internal data.

In simple words:

Encapsulation = Data hiding + Controlled access

Real-Life Example: Bank Account

Think about a bank account. You can deposit money, withdraw money, and check your balance, but you cannot directly change the balance to any value you want.

For example, you should not be able to directly set your balance to ₹1,00,00,000. Instead, the bank provides controlled operations such as deposit(), withdraw(), and getBalance(). The actual balance is kept private and can only be accessed or modified through these valid operations.

How Encapsulation Works in Java

There are a few important concepts involved:

ConceptPurpose
privateHides the internal data
public methodsProvide controlled access
GetterAllows reading data
SetterAllows modifying data
ValidationPrevents invalid data

Java Example

class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}

Using the Class

BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(300);
System.out.println(account.getBalance()); // 700

Why is balance Private?

If balance were public:

class BankAccount {
public double balance;
}
BankAccount account = new BankAccount();
account.balance = -5000; // Invalid value

Anyone could directly modify the balance.

By making it private:

class BankAccount {
private double balance;
}

the outside code cannot directly access or modify it. Instead, it must go through methods where we can apply rules and validation.

Encapsulation vs Data Hiding

These terms are related but not exactly the same.

EncapsulationData Hiding
Bundles data and methods togetherRestricts access to internal data
Achieved through classesCommonly achieved using private
Broader conceptPart of encapsulation

Key Benefits

BenefitExplanation
Data ProtectionPrevents direct modification
ValidationAllows checking data before changing it
ControlDecides how data can be accessed
MaintainabilityInternal implementation can change without affecting users
SecurityHides sensitive internal details

Interview Definition

Encapsulation is an OOP principle that bundles data and the methods that operate on that data within a class while restricting direct access to the internal state.

Remember

Private data + controlled public methods = Encapsulation

Next TopicInheritance