Lesson 19 of 34 · Classes & Objects
Java Encapsulation: private Fields, Getters and Setters
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
depositandwithdraw, notsetBalance. - 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 balanceandint transactions BankAccount(String owner, int initialBalance)— a negative initial balance is stored as0- getters
String getOwner(),int getBalance()andint getTransactionCount() void deposit(int amount)— addsamountto the balance; amounts<= 0are ignoredboolean withdraw(int amount)— ifamountis positive and not more than the balance, subtracts it and returnstrue; otherwise it changes nothing and returnsfalse- 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(); // 2Premium 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
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 .