Java Encapsulation
Encapsulation means bundling an object's data together with the methods that work on it, and hiding the data from the outside world. Other code can't poke at the fields directly; it must go through methods that the class chooses to offer. That way the class stays in control of its own state and can guarantee it is always valid.
The problem with public fields
class Thermostat {
double target; // anyone can set anything
}
class Main {
public static void main(String[] args) {
Thermostat t = new Thermostat();
t.target = -273.5; // nonsense, but nothing stops it
System.out.println("Target: " + t.target);
}
}Target: -273.5
Once a field is public, every class in the program can break the rules, and you can't change how the data is stored without breaking all that code.
Private fields with getters and setters
The standard recipe:
- Make fields
private. - Provide a public getter (
getX, orisXfor booleans) to read a value. - Provide a public setter (
setX) only if outsiders should be allowed to change it — and validate inside it.
class Thermostat {
private double target = 20.0;
private boolean ecoMode;
public double getTarget() {
return target;
}
public void setTarget(double target) {
if (target < 5 || target > 30) {
System.out.println("Ignored invalid target " + target);
return;
}
this.target = target;
}
public boolean isEcoMode() {
return ecoMode;
}
public void setEcoMode(boolean ecoMode) {
this.ecoMode = ecoMode;
}
}
class Main {
public static void main(String[] args) {
Thermostat t = new Thermostat();
t.setTarget(22.5);
t.setTarget(-273.5);
t.setEcoMode(true);
System.out.println("Target: " + t.getTarget() + ", eco: " + t.isEcoMode());
// t.target = 99; // error: target has private access in Thermostat
}
}Ignored invalid target -273.5
Target: 22.5, eco: true
Read-only and computed properties
Not every field needs a setter. Leaving it out makes the value read-only from the outside. A getter can also compute a value rather than return a stored field — callers can't tell the difference:
class BankAccount {
private final String owner;
private long balanceCents;
private int transactions;
BankAccount(String owner) {
this.owner = owner;
}
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("Deposit must be positive");
balanceCents += cents;
transactions++;
}
public boolean withdraw(long cents) {
if (cents <= 0 || cents > balanceCents) return false;
balanceCents -= cents;
transactions++;
return true;
}
public String getOwner() { return owner; }
public int getTransactionCount() { return transactions; }
public String getBalance() { // computed from the stored cents
return String.format("%d.%02d", balanceCents / 100, balanceCents % 100);
}
}
class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Noor");
acc.deposit(12_000);
System.out.println("Withdraw 50.00: " + acc.withdraw(5_000));
System.out.println("Withdraw 500.00: " + acc.withdraw(50_000));
System.out.println(acc.getOwner() + " has " + acc.getBalance()
+ " after " + acc.getTransactionCount() + " transactions");
}
}Withdraw 50.00: true
Withdraw 500.00: false
Noor has 70.00 after 2 transactions
There's no setBalance — the only way to change the balance is through deposit and withdraw, which enforce the rules.
Protecting mutable internals
Returning a reference to an internal array or list lets callers modify it behind your back. Return a copy or an unmodifiable view instead:
import java.util.ArrayList;
import java.util.List;
class Playlist {
private final List<String> songs = new ArrayList<>();
public void add(String song) {
songs.add(song);
}
public List<String> getSongs() {
return List.copyOf(songs); // read-only snapshot
}
}
class Main {
public static void main(String[] args) {
Playlist p = new Playlist();
p.add("Song A");
p.add("Song B");
List<String> view = p.getSongs();
try {
view.add("Sneaky song");
} catch (UnsupportedOperationException e) {
System.out.println("Can't modify the playlist from outside");
}
System.out.println(p.getSongs());
}
}Can't modify the playlist from outside
[Song A, Song B]
Benefits
| Benefit | Why |
|---|---|
| Validity | setters and methods reject bad values |
| Flexibility | internal representation can change without affecting callers |
| Read-only / write-only data | simply omit the setter or getter |
| Easier debugging | every change goes through a method you can log or breakpoint |
Tip: Don't generate getters and setters for every field by reflex. Ask what operations make sense for the object (
deposit,withdraw) and expose those. For simple immutable data carriers, Java'srecord(see the Records chapter) writes the boilerplate for you.
Test yourself
What is the usual access modifier for fields in an encapsulated class?
- public
- protected
- private
- static
What is the conventional getter name for a boolean field active?
- getActive()
- isActive()
- active()
- hasActive()
How do you make a property read-only to other classes?
- Make it public final
- Provide a getter but no setter
- Provide a setter but no getter
- Make it static