2.5.1 Introduction to Encapsulation

Video: Encapsulation (7:10)
Introduction to Encapsulation

The Wildcats training application stores player information and records turns. As more code uses those objects, the Player class needs control over how its information changes.

Let an object own its state

A turn count is state. Recording a permitted turn is behavior. If every caller can replace the count, each caller must remember the training rules.

Separate requests from storage

Imagine a teaching rule that allows at most three training turns. A caller should request one turn; Player decides whether to accept it. This is an application rule, not an official soccer regulation.

Two ways to interact
Caller request What the caller must know
Assign a turn count directly The storage field and every rule about its value
Request a turn The public action and what its result means

A private field remains part of each object. Code in the declaring class can use it, while ordinary code in another class cannot access it directly. Public operations make the object useful without exposing every field.

Protect decisions as well as data

Private storage alone does not guarantee good rules. A public operation that accepts any count can still produce an invalid count. The operation must enforce the intended behavior.

Apply the idea
Check your understanding