Skip to content
Codewilds

Lesson 19 of 34 · Classes & Objects

Java Encapsulation: private Fields, Getters and Setters

medium20 XP3 min read

Imagine a bank whose account class has a public balance field. Any line of code anywhere in the program could write account.balance = -1_000_000; — and nothing would stop it. Encapsulation fixes that: an object keeps its data private and lets the outside world change it only through methods that enforce the rules.

Access modifiers

Java controls who may see a field or method with access modifiers:

Modifier Visible from
private only inside the same class
(none) — package-private classes in the same package
public everywhere
class Thermostat {
    private double target = 20.0;
}

Thermostat t = new Thermostat();
t.target = 99;   // compile error: target has private access in Thermostat

The usual rule in Java: fields are private, and the methods that form the class's public face are only as visible as they need to be.

Getters and setters

To let other code read a private field, add a getter. To let it change the field safely, add a setter that checks the new value first:

class Thermostat {
    private double target = 20.0;

    double getTarget() {
        return target;
    }

    void setTarget(double target) {
        if (target < 5 || target > 30) {
            return;              // ignore unsafe values
        }
        this.target = target;
    }
}

Getters are named getX() — or isX() for booleans, like isOpen() — and setters setX(...). Now every change goes through setTarget, so no code can ever set the thermostat to 99 degrees.

Silently ignoring a bad value can hide a bug. The alternative is to refuse it loudly by throwing an exception, which stops the program with an error message:

if (target < 5 || target > 30) {
    throw new IllegalArgumentException("target must be between 5 and 30");
}

You will learn to catch exceptions in Chapter 6; for now it is enough to know that throw rejects invalid input.

Read-only fields with final

Not every field needs a setter. A final field must be assigned exactly once — in its declaration or in the constructor — and can never change afterwards:

class Passport {
    private final String number;

    Passport(String number) {
        this.number = number;
    }

    String getNumber() {
        return number;
    }
}

A getter without a setter makes the value read-only for everybody else.

Why bother?

  • Invariants: the class guarantees its own rules ("the balance is never negative") instead of trusting every caller.
  • Freedom to change: you can switch the internal representation — say, store cents instead of a double — without breaking any code that only calls the methods.
  • Easier debugging: if a value is wrong, only a handful of methods could have changed it.

Common mistakes

  • Public fields "for convenience" — they defeat the whole point.
  • A setter for every field by reflex. Offer only the operations the object really supports: a bank account has deposit and withdraw, not setBalance.
  • Forgetting this. in a setter: target = target; assigns the parameter to itself.
  • Validating in the setter but not in the constructor, so an invalid object can still be created.

Assignment

Complete the class BankAccount:

  • private fields: final String owner, int balance and int transactions
  • BankAccount(String owner, int initialBalance) — a negative initial balance is stored as 0
  • getters String getOwner(), int getBalance() and int getTransactionCount()
  • void deposit(int amount) — adds amount to the balance; amounts <= 0 are ignored
  • boolean withdraw(int amount) — if amount is positive and not more than the balance, subtracts it and returns true; otherwise it changes nothing and returns false
  • only successful deposits and withdrawals count as transactions
BankAccount account = new BankAccount("Aria", 100);
account.deposit(50);            // balance 150
account.withdraw(500);          // false — balance stays 150
account.withdraw(30);           // true  — balance 120
account.getTransactionCount();  // 2

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Encapsulation and properties in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 19 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.