Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Imagine an ATM machine. You can deposit and withdraw money — but you can't directly touch the cash inside. The machine controls HOW you interact with the money. That's encapsulation — hiding internal data and exposing controlled access.

Real World Analogy

Your phone has a battery inside. You can't directly touch the battery cells. But you can charge it via the charging port. The port = getter/setter. The battery = private field.

What is Encapsulation?

Bundling data (fields) and methods that operate on that data into a single unit (class), and restricting direct access to the fields.
Two steps:
  1. #
    Make fields private
  2. #
    Provide public getters/setters to access them
java
QUBITS OF DPK
1class BankAccount {
2    private double balance;      // hidden!
3    private String accountHolder;
4
5    // Getter
6    public double getBalance() {
7        return balance;
8    }
9
10    // Setter with validation
11    public void setBalance(double balance) {
12        if (balance < 0) {
13            System.out.println("Invalid amount!");
14            return;
15        }
16        this.balance = balance;
17    }
18}

Why Encapsulation Matters

java
QUBITS OF DPK
1// WITHOUT encapsulation — dangerous
2class BankAccount {
3    public double balance;
4}
5BankAccount acc = new BankAccount();
6acc.balance = -99999;   // 💥 no validation possible!
7
8// WITH encapsulation — controlled
9acc.setBalance(-99999);  // ✅ validation catches this

Getters and Setters

java
QUBITS OF DPK
1class Student {
2    private String name;
3    private int age;
4    private double cgpa;
5
6    // Getters
7    public String getName()  { return name; }
8    public int    getAge()   { return age;  }
9    public double getCgpa()  { return cgpa; }
10
11    // Setters with validation
12    public void setName(String name) {
13        if (name == null || name.isEmpty()) return;
14        this.name = name;
15    }
16
17    public void setAge(int age) {
18        if (age < 0 || age > 150) return;
19        this.age = age;
20    }
21
22    public void setCgpa(double cgpa) {
23        if (cgpa < 0.0 || cgpa > 10.0) return;
24        this.cgpa = cgpa;
25    }
26}

Production Use Case

java
QUBITS OF DPK
1// Stripe Payment Service
2class PaymentRequest {
3    private double amount;
4    private String currency;
5
6    public void setAmount(double amount) {
7        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
8        this.amount = amount;
9    }
10    // Getter/Setter ensures no invalid payment ever reaches the gateway
11}

Benefits of Encapsulation

javascript
QUBITS OF DPK
11. Data hiding         — internal state protected
22. Validation          — invalid data rejected at setter
33. Flexibility         — change internal implementation without affecting external code
44. Read-only fields    — provide only getter, no setter
55. Write-only fields   — provide only setter, no getter (passwords!)

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Forgetting 'this' in setter
2public void setAge(int age) {
3    age = age;      // ❌ field not updated!
4    this.age = age; // ✅
5}
6
7// Trap 2 — Returning mutable object from getter
8public Date getDate() {
9    return date;   // ⚠️ caller can modify your internal date!
10    return new Date(date.getTime());  // ✅ return copy
11}
12
13// Trap 3 — Encapsulation ≠ just private fields
14// Must ALSO have meaningful validation in setters

30-Second Interview Answer

"Encapsulation is the OOP principle of bundling data and methods together while hiding internal state. Fields are made private and accessed via public getters/setters. This ensures validation before data modification, prevents invalid states, and allows internal implementation to change without breaking external code. A classic example is a BankAccount where balance can't go negative — the setter enforces this rule."

Interview Questions & MAANG-Level Answers

Q1. What is encapsulation and why is it important?
Encapsulation is the OOP principle of bundling data (fields) and methods together inside a class, while restricting direct access to fields using private. Importance: prevents invalid state (setter validates before setting), hides implementation details (change internal logic without breaking callers), enables controlled access (read-only, write-only fields), and improves maintainability. Without encapsulation: account.balance = -99999 is possible and causes silent corruption.
Q2. What is the difference between private and public fields?
private fields are only accessible within the same class — not even subclasses or same package. This enforces encapsulation. public fields are accessible everywhere, allowing direct modification without validation. In production, fields should ALWAYS be private with public getter/setter methods. Exception: public static final constants (e.g., PI) since they're immutable.
Q3. How do getters and setters support encapsulation?
Getters and setters are controlled access points to private fields. Setters add validation logic before assignment:
java
QUBITS OF DPK
1public void setAge(int age) {
2    if (age < 0 || age > 150) throw new IllegalArgumentException("Invalid age");
3    this.age = age;  // only set if valid
4}
Getters control what is returned — can return a defensive copy instead of the actual reference. They also allow read-only (getter only) or write-only (setter only) access patterns.
Q4. Can you have a read-only field in Java? How?
Yes — two approaches: (1) Provide only a getter, no setter: public int getId() { return id; } — external code can read but not write. (2) private final field initialized in constructor — once set, cannot change:
java
QUBITS OF DPK
1class User {
2    private final String userId;  // set once in constructor
3    User(String id) { this.userId = id; }
4    public String getUserId() { return userId; }
5    // No setter — truly read-only
6}
Q5. What is data hiding?
Data hiding is the concept of restricting access to internal object state — it's the primary goal of encapsulation. By making fields private, the internal representation is hidden from outside. Callers interact only through the defined public interface (methods). This allows you to completely change the internal implementation (e.g., change int age to LocalDate birthDate and compute age) without any callers knowing or being affected.
Q6. Why should getters not return references to mutable internal objects?
If a getter returns a direct reference to an internal mutable object, callers can modify it without going through the setter, bypassing validation:
java
QUBITS OF DPK
1// DANGEROUS
2public List<String> getItems() { return items; }  // caller can items.clear()!
3// SAFE — return defensive copy
4public List<String> getItems() { return new ArrayList<>(items); }
5// Or return unmodifiable view
6public List<String> getItems() { return Collections.unmodifiableList(items); }
This is known as the "broken encapsulation" or "leaking internal state" anti-pattern.