Script Valley
Java: Complete Language Course
Object-Oriented Programming in JavaLesson 2.2

Java encapsulation with private fields and getters setters

access modifiers, private fields, public getters, public setters, data hiding, validation in setters, encapsulation principle

Encapsulation

Encapsulation hides a class's internal state and forces external code to interact through controlled methods. This lets you add validation, change internal representation, or compute derived values without breaking callers.

Before Encapsulation — Fragile

public class Account {
    public double balance; // anyone can set this to -999
}

After Encapsulation — Controlled

public class Account {
    private double balance;
    private String owner;

    public Account(String owner, double initialBalance) {
        this.owner = owner;
        setBalance(initialBalance);
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double amount) {
        if (amount < 0) {
            throw new IllegalArgumentException("Balance cannot be negative");
        }
        this.balance = amount;
    }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Deposit must be positive");
        balance += amount;
    }
}
Account acc = new Account("Alice", 1000);
acc.deposit(500);
System.out.println(acc.getBalance()); // 1500.0
acc.setBalance(-100); // throws IllegalArgumentException

Make every field private by default. Add getters only when external code genuinely needs to read a value. Add setters only when external mutation is required — and validate inside them.

A class with no setters and all fields set at construction time is effectively immutable. Immutable objects are inherently thread-safe and easier to reason about, so prefer them when the data does not need to change after creation.

Encapsulation also enables future-proofing: if you later decide to store balance in cents instead of floating-point dollars for precision, you change only the private field and setter — no callers break. Public fields make such refactoring impossible without touching every usage site.

Up next

Java inheritance and the extends keyword

Sign in to track progress