Encapsulation in Java - Explained Simply
What is Encapsulation?
Encapsulation means hiding the internal data of a class and only allowing access through methods.
It's like keeping your important things in a locker and giving access to only trusted people using a
key.
Real-Time Example (Bank Account)
Imagine you have a bank account:
- Your balance is private.
- You can deposit or withdraw using methods.
- You cannot directly change the balance.
Java Code 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;
} else {
System.out.println("Invalid withdrawal");
public double getBalance() {
return balance;
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(200);
System.out.println("Current Balance: " + account.getBalance());
Why Use Encapsulation?
- To protect data from direct modification.
- To control who can change or see the data.
- To hide implementation details.
Interview Questions and Answers:
Q1. What is Encapsulation in Java?
A: Encapsulation is wrapping data (variables) and methods into a single unit (class) and restricting
direct access using access modifiers like private.
Q2. Why is Encapsulation used in Java?
A: To protect sensitive data, implement control, and improve code maintenance and security.
Q3. Can you give a real-life example of encapsulation?
A: A bank ATM is a real-world example. You insert your card, enter a PIN, and access is controlled.
Q4. How is encapsulation implemented in Java?
A: By declaring class variables as private and using public getters and setters to access and update
values.