Card 08/ 08
Recap: Encapsulation
Private fields, access levels, leaking references and composition, with where each was.
Encapsulation comes down to the five ideas below, each listed with the card that covers it.
| The idea | Where |
|---|---|
private reduces the number of places a rule has to be written to one | Encapsulation: Private Fields and the Methods That Guard Them |
Four access levels, and protected is wider than no keyword | Java Access Modifiers: private, Package-Private, protected and public |
private protects the variable and not the object it points at | Why a private List Returned by a Getter Is Not private |
| Copy on the way in as well as on the way out | Defensive Copies: The Same Leak Through a Constructor |
extends exposes the whole parent; a field exposes what you chose | Composition vs Inheritance |
Hiding a variable is easy and hiding an object takes a copy. A class whose fields are all immutable values is encapsulated the moment they are private; a class holding collections is not, until something stops the references escaping.
← → move through sections and cards