Simplifying OOP in Java: Encapsulation
Software Engineering

Simplifying OOP in Java: Encapsulation

A simple introduction to encapsulation in Java, showing why private and public matter and how getters and setters help protect data inside a class.

April 18, 2026·3 daqiiqaa dubbisuu·koofkee

Day 2: Encapsulation

After understanding classes, objects, and instances, the next important step in OOP is encapsulation.

Encapsulation is the idea of keeping data inside a class and controlling how it is accessed or changed.

In Java, this is usually done by making variables private and exposing controlled methods such as getters and setters.

Why private matters

When a variable is marked as private, it cannot be accessed directly from outside the class.

That helps protect the data and prevents careless changes.

Why public methods matter

If the data is hidden, we still need a way to read or update it when necessary.

That is why we often use public methods such as getters and setters.

These methods allow controlled access to the data.

Example

class Car {
    private int speed;

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        if (speed >= 0) {
            this.speed = speed;
        }
    }
}
  • speed is private, so it cannot be changed directly from outside the class
  • getSpeed() reads the value
  • setSpeed() updates the value only if it is valid

This is the real idea behind encapsulation.

The class protects its own data and decides how that data should be used.

Encapsulation is not only about hiding variables.

It is about protecting data and controlling change in a clean and structured way.

Java, OOP, Encapsulation, Software Engineering, Computer Science, Beginner Java, Koofkee