Skip to the guide

Encapsulation: hiding state behind methods

BeginnerConcept6 pages

Encapsulation means a class keeps its fields private and lets callers change them only through methods that keep its rules. The last page showed how a public field breaks a rule. In the round, the interviewer goes one step further and asks whether private fields are enough on their own.

The day trip organiser's sign-up sheet

Think of a friend who organises a minibus day trip to the coast. The bus has ten seats, and she keeps the sign-up sheet in her bag. You message her "put me down", and she adds your name only if a seat is free and you aren't on the sheet already. When someone asks who's coming, she sends them a photo of the sheet. Nobody else ever writes on it.

Now picture a second organiser. Her sheet is in her bag too, but she hands it to anyone who asks to look. It comes back with an eleventh name squeezed in at the bottom. The "10 seats" at the top is written in pencil, and anyone may rub it out and write a new number.

In code, the trip is a class, Tour, with a fixed number of seats. The sheet is a private list of passengers, and the ten seats are a private seats field. The organiser is the methods book and cancel, which check the rules before they change the list. The photo is a read-only copy of the list, and the Reminders class reads that copy when it texts the passengers. Messaging the organiser instead of writing on the sheet yourself has a name, tell, don't ask: you tell the object what you want, instead of reading its data and doing the job yourself. The second organiser is a class with a getter and a setter for every field.