Intermediate 25 min read

Encapsulation

By the end of this lesson, you'll be able to:

  • Define encapsulation as bundling data with the logic that protects it
  • Explain why encapsulation reduces bugs caused by invalid state
  • Refactor a class with exposed fields into one with proper encapsulation

Prerequisites: Module 10: "Classes and Objects"

Naming what Module 10 already previewed

The private balance + public getBalance() pattern from Module 10's Access Modifiers lesson has a name: encapsulation. It's the first of the four core object-oriented principles this module covers — encapsulation, inheritance, polymorphism, and (via composition) code reuse without inheritance.

A real business example: Fleet Management

public class DeliveryVehicle {
    private Decimal fuelLevel;

    public DeliveryVehicle(Decimal startingFuel) {
        this.fuelLevel = startingFuel;
    }

    public void refuel(Decimal amount) {
        if (amount > 0) {
            fuelLevel += amount;
        }
    }

    public Decimal getFuelLevel() {
        return fuelLevel;
    }
}
  1. public class DeliveryVehicle { — the class.
  2. private Decimal fuelLevel; — private means nothing outside this class can touch fuelLevel directly.
  3. (blank line)
  4. public DeliveryVehicle(Decimal startingFuel) { — the constructor.
  5. this.fuelLevel = startingFuel; — sets the starting fuel through controlled code, not a direct outside assignment.
  6. } — closes the constructor.
  7. (blank line)
  8. public void refuel(Decimal amount) { — the only way outside code can change fuelLevel upward.
  9. if (amount > 0) { — enforces a business rule: only positive amounts count.
  10. fuelLevel += amount; — adds the fuel.
  11. } — closes the if.
  12. } — closes refuel().
  13. (blank line)
  14. public Decimal getFuelLevel() { — a controlled, read-only window onto the value.
  15. return fuelLevel; — returns it.
  16. } — closes the method.
  17. } — closes the class.

fuelLevel can never go directly negative or be corrupted from outside — every change is forced through refuel(), which enforces rules like "only positive amounts count." A fleet system with hundreds of vehicles stays trustworthy because no code anywhere can bypass this.

What breaks without encapsulation

public class DeliveryVehicle {
    public Decimal fuelLevel; // no protection at all
}

DeliveryVehicle van = new DeliveryVehicle();
van.fuelLevel = -9999; // perfectly legal, completely nonsensical
  1. public class DeliveryVehicle { — the class.
  2. public Decimal fuelLevel; — a plain public field, with no protection at all.
  3. } — closes the class.
  4. (blank line)
  5. DeliveryVehicle van = new DeliveryVehicle(); — creates a vehicle.
  6. van.fuelLevel = -9999; — perfectly legal Apex, completely nonsensical in reality — with a public field, literally any code anywhere in the org can set fuelLevel to anything, including impossible values, and there's no single place to add a rule later.

Exercise

Refactor this class so odometerReading is private, only increases through a method addDistance(Decimal km) that ignores negative input.

Show hint

private Decimal odometerReading; public void addDistance(Decimal km) { if (km > 0) { odometerReading += km; } }

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Encapsulation Quiz

1. What does encapsulation protect against?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Encapsulation means bundling an object's data together with the methods that are allowed to change it, so nothing outside the class can put that data into an invalid state.