Encapsulation

Basic Java
≈ 3 min read

An object manages its own state

An object has fields, but that does not mean any code should be able to change them however it wants. If internal state is directly accessible, outside code can easily write a value that leaves the object in an invalid state.

Encapsulation helps draw a boundary: the details of how data is stored stay inside the class, while outside code works with the object through allowed operations. This lets the class control which changes are valid.

Closing fields with private

The private modifier makes a class member accessible only inside that class. That is why fields that represent an object's internal state are usually hidden from direct access.

class Thermostat {
    private int temperature = 20;

    public int getTemperature() {
        return temperature;
    }

    public void increase() {
        if (temperature < 30) {
            temperature++;
        }
    }

    public void decrease() {
        if (temperature > 10) {
            temperature--;
        }
    }
}

Here, the temperature is stored in a private field. Outside code cannot write thermostat.temperature = 100 and bypass the class rules. It can only call public methods, and those methods do not allow the temperature to go outside the range from 10 to 30.

private hides access, not the existence of the data itself. The field is still part of the object — it can simply be changed directly only by code inside the class.

public is the allowed entry point into an object

The public modifier is used for operations that the class intentionally exposes to outside code. In the example above, getTemperature(), increase(), and decrease() form the public way to work with the thermostat.

The main benefit here is not that the field is “hidden,” but that the class keeps control over its state. If the rule for changing the temperature changes later, outside code can keep calling the same methods, while the check can be changed inside the class.

Getters and setters are not the goal of encapsulation

A common mistake is to make every field private and then add a plain getter and setter for each one without any rules. Direct access is technically gone, but outside code can still assign almost any value to the field.

That is why not every field necessarily needs a setter. Sometimes it is better to provide operations that reflect the meaning of the object: for example, increase() and decrease() instead of setTemperature(int temperature). This makes it clear from the code what the object is allowed to do.

Encapsulation is about controlling an object's state. private helps hide the details, while public methods define a safe way to work with them.