2.5.10 Accessing Private Fields Through Class Methods

Video: Wrapper Methods (17:27)
Accessing Private Fields Through Class Methods

A caller can ask how many turns Jordan has taken without receiving permission to replace the count. The return value is an answer, not the private field itself.

Read through a public query

Use the complete Player definition from the controlled-access lesson.

Statements inside a caller method
Player jordan = new Player();
bool accepted = jordan.RecordTurn();
int displayedTurns = jordan.GetNumberOfTurns();

The request succeeds, so accepted is true and displayedTurns becomes 1. Inside Player, GetNumberOfTurns reads its private field and returns that integer.

Separate a snapshot from live state
Continue the same caller
displayedTurns = 99;
int actualTurns = jordan.GetNumberOfTurns();

actualTurns is still 1. Changing the local integer changes only the local copy. If Jordan records another turn, an earlier displayedTurns value does not update automatically; call the query again to refresh it.

Apply the idea
Check your understanding