Encapsulation Abstract Art
lock OOP Fundamentals

What is Encapsulation?

Encapsulation is the practice of bundling data (variables) and methods (functions) into a single unit—and restricting direct access to some of that object's components.

"Think of it as a protective capsule. The data is the medicine inside, and the capsule shell controls how it dissolves and interacts with the body."

shield_lock

Protection

Prevents objects from reaching invalid states (e.g., a negative bank balance) by validating all inputs.

build_circle

Flexibility

Allows you to change internal logic (how data is stored or calculated) without breaking code that uses the object.

visibility_off

Hiding Complexity

Exposes a clean, simple "Public API" (methods) while hiding the messy "Private Implementation" details.

account_balance

Interactive Simulation: The Bank Vault

Simulate Data Access

See what happens when you try to access data directly versus using encapsulated methods.

warning Direct Access (Public Fields)

The balance variable is public. Anyone can set it to ANY value, even invalid ones like -500 or "banana". The object has no control.

Try entering a negative number!

terminal System Output
> System initialized in UNSECURE mode.
> Waiting for input...
account_balance_wallet

MyAccount

id: #882190

Unsecured
lock_open

Current Balance

$0.00

public double balance;

code The Code Difference

cancel Without Encapsulation BadPractice.java
public class BankAccount {
    // ⚠️ DANGEROUS: Public access allowed
    public double balance;Anyone can change this variable directly to ANY value!

    // No methods to control logic
}

// Usage:
BankAccount myAcct = new BankAccount();
myAcct.balance = -5000; // 😱 Oh no!
// The bank is now broken.
check_circle With Encapsulation GoodPractice.java
public class BankAccount {
    // 🔒 SAFE: Private access only
    private double balance;Only methods INSIDE this class can touch this variable.

    // Public method controls the rules
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        } else {
            System.out.println("Invalid!");
        }
    }
    
    // Read-only access
    public double getBalance() {
        return balance;
    }
}

Concrete Benefits

rule

1. Validation & Logic Control

Without encapsulation, you can set an age to -5. With encapsulation, the setter method intercepts the change and validates it first.

public void setAge(int age) {
  if (age >= 0 && age < 120) {
    this.age = age;
  } else {
    throw new IllegalArgumentException("Invalid age");
  }
}
published_with_changes

2. Change Internal Logic Freely

Imagine you want to change the balance variable from a double to a BigDecimal for better precision. If fields were public, every single file using your class would break. With encapsulation, you change the private field, update the getter/setter internals, and no external code breaks.

lock

3. Read-Only Data

Sometimes you want data to be visible but not changeable (like a User's ID). Encapsulation makes this trivial: just provide a getId() method but do not provide a setId() method.