What is encapsulation, and how does a class use it to protect its own state?
Encapsulation is the practice of keeping a class's data private and exposing only the operations that are allowed to work on it. The point is not secrecy for its own sake. It is that the class becomes the only thing that can change its own state, so the class itself is responsible for keeping that state valid.
public class Main {
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(21.5);
System.out.println(t.celsius() + "C = " + t.fahrenheit() + "F");
try {
t.setCelsius(-500);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
class Temperature {
private double celsius;
void setCelsius(double value) {
if (value < -273.15) {
throw new IllegalArgumentException("below absolute zero");
}
celsius = value;
}
double celsius() { return celsius; }
double fahrenheit() { return celsius * 9 / 5 + 32; }
}The temperature class shows the mechanism. The field is private, so the only way in is the setter, and the setter rejects a value below absolute zero. The exception is thrown at the point of the bad write, so the invalid value never enters the object. A caller that tries gets an immediate, explanatory failure instead of a corrupted object that misbehaves later.
Notice that the class still offers everything a caller legitimately needs: reading the temperature in either unit, and setting a valid one. Encapsulation is not about hiding functionality. It is about routing every mutation through a place where the rules can be enforced.
The benefit shows up over time. If a rule changes, say the unit becomes Kelvin internally, you edit one class and every caller keeps working. If the field were public, every caller would have to be updated, and any caller that forgot would silently corrupt the object.