Stop 04 · Classes & ObjectsTopics · 4/8

Encapsulation (Getters & Setters)

Part of the Java Roadmap

In short

Encapsulation is the first pillar of object-oriented programming and an interview staple. The idea is simple: an object guards its own data, so it can never be put into a broken state.

Encapsulation means hiding internal state behind methods so objects stay valid. Private fields with getters and validated setters are the common pattern.

The jaadu sits behind a small barred bank window, checking a paper slip, with a heavy round vault door closed in the background.

Think of it like this

The bank teller window

You cannot walk into the vault and grab cash. You go to the teller window, fill in a slip, and the teller checks your balance before handing over money. Private fields are the vault; getters and setters are the teller window that checks every request.

Watch it happen

Trying to set a bad value

Caller
setMarks()
private marks

setMarks(85)

1/4The caller cannot touch the field directly, so it asks the setter.

The big ideas

What you need to know

private fields

Nothing outside the class can change them directly.

Getters read

getName(), and isActive() for booleans. Return copies of mutable things like lists if callers should not change them.

Setters validate

setMarks checks the range before storing. Bad data is rejected at the door.

Not every field needs a setter

An account number should never change. Leave out the setter, or make the field final.

See it in code

Walk through the code

java
1public class Employee {2    private final String empId;3    private String name;4    private double monthlySalary;5 6    public Employee(String empId, String name, double monthlySalary) {7        this.empId = empId;8        setName(name);9        setMonthlySalary(monthlySalary);10    }11 12    public String getEmpId() { return empId; }13 14    public String getName() { return name; }15 16    public void setName(String name) {17        if (name == null || name.isBlank()) {18            throw new IllegalArgumentException("Name is required");19        }20        this.name = name.strip();21    }22 23    public double getMonthlySalary() { return monthlySalary; }24 25    public void setMonthlySalary(double salary) {26        if (salary < 0) {27            throw new IllegalArgumentException("Salary cannot be negative");28        }29        this.monthlySalary = salary;30    }31 32    public double getAnnualSalary() {33        return monthlySalary * 12;34    }35}

1/4All data is private. empId is final because it should never change.

Private fields, validated setters, no setter for the ID, and a computed getter with no field behind it.

Save yourself the pain

Common mistakes

Oops

Generating a getter and setter for every field automatically.

Do this instead

That is public fields with extra steps. Only expose what callers need, and validate what they can change.

Oops

Returning a private List directly from a getter.

Do this instead

Callers can then add or remove items. Return List.copyOf(items) or an unmodifiable view.

Your mission

Protect a product

~20 min

Quick check

What is the main benefit of a setter over a public field?

Go deeper

  1. 1Add a setter that rejects a negative age or balance.
  2. 2Skip setters for fields that should never change after creation.
  3. 3Use IntelliJ to generate getters and setters, then review them.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge