What is encapsulation in Java, and why bother with getters and setters if the field could just be public?
Encapsulation means keeping the data of a class private and letting the class decide what may be done with it. The outside world talks to the class through a small set of methods, and those methods hold the rules.
You might wonder why you would not just make the field public and save the work. There are four good reasons.
The first one is validation. A setter can refuse a value that makes no sense, so the object can never hold a bad state.
The second one is that you can change how the data is stored later. If a field is public, every piece of code that uses it depends on the exact way it is stored. If it is private, you are free to store it in a different shape and change only the one class.
The third one is that a getter can do something useful, such as working out a value that is cheaper to keep than to work out each time.
The fourth one is that you can control when a value changes. A setter can check that the change is allowed, can write to a log, or can tell other parts of the program that something happened.
public class Main {
public static void main(String[] args) {
Temperature temperature = new Temperature();
temperature.setCelsius(25.0);
System.out.println("celsius : " + temperature.getCelsius());
System.out.println("fahrenheit : " + temperature.getFahrenheit());
// The setter refuses the value, so the object stays valid.
try {
temperature.setCelsius(-300.0);
} catch (IllegalArgumentException e) {
System.out.println("refused : " + e.getMessage());
}
System.out.println("still : " + temperature.getCelsius());
}
}
class Temperature {
private double celsius;
public void setCelsius(double value) {
if (value < -273.15) {
throw new IllegalArgumentException("below absolute zero");
}
this.celsius = value;
}
public double getCelsius() {
return this.celsius;
}
public double getFahrenheit() {
return this.celsius * 9 / 5 + 32;
}
}
One warning is worth giving. A class where every field has a getter and a setter that does nothing else is sometimes called an anemic class, and it is not really encapsulation. Encapsulation means that the class holds the rules, and a getter that gives the raw value away with no check at all is giving those rules away.
The next question in this topic compares encapsulation with abstraction.