What is encapsulation in Java, and why bother with getters and setters if the field could just be public?
Encapsulation means keeping an object's state private and controlling every change to it through methods the class itself provides. The point is not the getters and setters — it is that the class, and only the class, decides what a valid state is.
A public field has no such guarantee. Anyone can write a nonsensical value and the object has no way to react. Once the field is private and every write goes through a method, you can validate the value, normalise it, keep a derived field in step, or log the change — and you can do all of that later without touching a single caller.
public class Main {
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(25.0);
System.out.println("celsius : " + t.getCelsius());
System.out.println("fahrenheit: " + t.getFahrenheit());
// The setter rejects invalid input instead of storing it.
try {
t.setCelsius(-500.0);
} catch (IllegalArgumentException e) {
System.out.println("rejected : " + e.getMessage());
}
System.out.println("unchanged : " + t.getCelsius());
}
}
class Temperature {
private double celsius;
public double getCelsius() {
return celsius;
}
public void setCelsius(double celsius) {
if (celsius < -273.15 || celsius > 1000) {
throw new IllegalArgumentException("out of range: " + celsius);
}
this.celsius = celsius;
}
public double getFahrenheit() {
return celsius * 9 / 5 + 32;
}
}The output shows what encapsulation buys. The bad value never reaches the field, so the object is still valid after the failed call, and the derived Fahrenheit reading can be computed from the single stored value instead of being a second field that could drift out of sync.
The counter-argument you will hear is that getters and setters are boilerplate that adds no safety. That is fair when they are pure accessors, and it is why the modern advice is to write accessors only when they earn their place — a validating setter, a computed getter, or a getter that returns a defensive copy. Java records and Lombok both exist because hand-writing trivial accessors is tedious, and both are reasonable answers to that objection.