What is encapsulation, and how does a class use it to protect its own state?
Encapsulation is the practice of keeping the internal data of a class private and putting every way of changing it behind a method that checks the values first. So the class protects its own state.
public class Main {
public static void main(String[] args) {
Temperature t = new Temperature();
t.setCelsius(21.5);
System.out.println(t.fahrenheit()); // 70.7
}
}
And here is the class, with the field private and the rules in the methods.
public 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 celsius() {
return celsius;
}
public double fahrenheit() {
return celsius * 9 / 5 + 32;
}
}
So how does the class use it to protect its own state? In three ways.
The first one is that the field is private, so no other class can write to it. The only way in is the setter, and the setter checks the value before it accepts it. So the temperature can never be below absolute zero, no matter what the caller does.
The second one is that the conversion lives next to the data. The Fahrenheit method knows the rule and it cannot get out of step with the Celsius value, because there is only one place that holds the number.
The third one is that the class can change its own mind later. If you decide to store the temperature in Kelvin instead, you change the field and the two methods. Every caller keeps working because they only used the methods.
without encapsulation with encapsulation
----------------------------- ------------------------------------
the field is public the field is private
any code can write a bad the setter refuses it
value
the rule is somewhere else the rule is in the class
changing the field breaks changing the field breaks
every caller nobody
And there is one detail worth knowing about, and it is the reason the setter checks at all. If the setter does not check, then the private field has not bought you anything except the inconvenience of a method. The protection comes from the check, not from the word private.
So the rule to remember is this. The private field keeps the code out, and the checks in the methods keep the data valid.
The next two questions in this topic are about what a public method gives you and about hiding a collection.