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;
}
}
fuelLevel can never go directly negative or be corrupted from outside — every change is forced through refuel(), which can enforce 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
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, because every caller touches the field directly instead of going through shared logic.
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; } }
Encapsulation Quiz
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.