1.1.25 Understanding Object State

Object State Is the Current Information Stored by an Object

An object's state is the collection of relevant values it holds at a particular moment.

A Player object's state might be:

Plain text
name = "Jordan"
jerseyNumber = 7
isAvailable = true

Those values can change while the Player object remains the same object.

Identity and State Are Different

Suppose:

C#
Player player1 = new Player();

Later:

C#
player1.jerseyNumber = 7;

and then:

C#
player1.jerseyNumber = 9;

The object identity has not changed.

The current state has.

Conceptually:

Plain text
same Player object
before → jerseyNumber = 7
after  → jerseyNumber = 9

State Develops as Statements Execute

Consider:

C#
Player player1 = new Player();
player1.name = "Jordan";
player1.jerseyNumber = 7;

Immediately after new, the fields may still contain default values.

After the first assignment, the name changes.

After the second assignment, the jersey number changes.

The final state is built through execution.

F10 Lets You Observe State Changes

A useful debugger workflow is:

  1. Pause before an assignment.
  2. Inspect the current object.
  3. Predict which field will change.
  4. Press F10.
  5. Inspect the object again.

For:

C#
player1.jerseyNumber = 7;

you may observe:

Plain text
before → jerseyNumber = 0
after  → jerseyNumber = 7

This turns an assignment from a line of syntax into an observable state transition.

Object State Can Include References

State is not limited to text, numbers, and Booleans.

A Player object may contain:

Plain text
team = reference to a Team object

Before the relationship is assigned:

Plain text
team = null

After:

C#
player1.team = team1;

the state changes:

Plain text
team → team1

The object now participates in a relationship.

UML Object Diagrams Show State Snapshots

A UML object diagram might show:

Plain text
player1 : Player
-------------------------
name = "Jordan"
jerseyNumber = 7

That is one modeled snapshot.

The code may pass through several earlier states before reaching it.

The debugger lets you compare the current runtime state with the intended UML snapshot.

State Explains Many Bugs

If a program behaves unexpectedly, ask:

This is often more precise than saying:

The object is wrong.

State Is Time-Specific

A debugger value is evidence from a particular moment.

If the program later executes another assignment, the state can change again.

Always connect an observed value to the current execution point.

The Main Idea

Object-oriented programs do not work only with class definitions.

They work with specific objects whose state changes over time.

Understanding that changing state is essential for explaining what the program is doing.