Card 08/ 08

RecapDifficulty: Advanced1 min

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.

What the topic established, and which card it was on
The ideaWhere
private reduces the number of places a rule has to be written to oneEncapsulation: Private Fields and the Methods That Guard Them
Four access levels, and protected is wider than no keywordJava Access Modifiers: private, Package-Private, protected and public
private protects the variable and not the object it points atWhy a private List Returned by a Getter Is Not private
Copy on the way in as well as on the way outDefensive Copies: The Same Leak Through a Constructor
extends exposes the whole parent; a field exposes what you choseComposition 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.