Encapsulation
Encapsulation limits how outside code can reach an object's state. A private field can be changed only through code inside its class.
Java has four access levels:
| Modifier | Accessible from |
|---|---|
private | The declaring class |
| No modifier | Classes in the same package |
protected | The same package and subclasses |
public | Any code that can reach the class |
Methods around that field create a place to enforce rules. The volume setter rejects a negative value, so the object cannot enter that invalid state through this API.
Protect a field
class AudioPlayer {
private int volume;
void setVolume(int volume) {
if (volume >= 0) {
this.volume = volume;
}
}
int getVolume() {
return volume;
}
}
public class Main {
public static void main(String[] args) {
AudioPlayer player = new AudioPlayer();
player.setVolume(80);
player.setVolume(-1);
System.out.println(player.getVolume());
}
}
Output:
80
The first setter call stores 80. The rejected second call leaves that valid value untouched.
Do not generate a setter for every field automatically. Immutable fields and purpose-specific methods often express the domain more accurately.
Keep temperature private. Accept values at or above -50 and return the stored value.