☕ Java

Encapsulation in Java

Encapsulation is about protecting your data. Make fields private, and control access through methods. It's the reason your bank balance can't be changed by just anyone who gets hold of your account object.

Why Hide Your Data?

Imagine a vending machine. You insert coins and press a button — you get your snack. You can't reach inside and grab items directly, you can't reset the counter, and you can't change the price. The machine's internals are hidden. You interact with it only through its defined interface (the buttons). That's encapsulation. Your class exposes controlled access points (methods), and hides the raw data (private fields). Why it matters: • Prevents accidental or malicious data corruption (no one can set your age to -500) • Lets you add validation in setters — reject bad data before it enters • Lets you change internal implementation without breaking code that uses the class • Makes code easier to test and maintain

Getters and Setters in Practice

Java
public class BankAccount {

    // private — cannot be accessed directly from outside this class
    private String owner;
    private double balance;

    public BankAccount(String owner, double initialBalance) {
        this.owner = owner;
        // Even in the constructor, we validate
        this.balance = (initialBalance > 0) ? initialBalance : 0;
    }

    // Getter — read-only access to balance
    public double getBalance() {
        return balance;
    }

    // No direct setter for balance — only controlled operations allowed
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        } else {
            System.out.println("Invalid deposit amount");
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds or invalid amount");
        }
    }

    public String getOwner() { return owner; }
}

// Usage
BankAccount acc = new BankAccount("Alice", 1000);
// acc.balance = 999999;  // Compile error — private field, can't touch it
acc.deposit(500);
System.out.println(acc.getBalance());  // 1500.0