1.1.25 Understanding Object State

Video: Fields (7:02)
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:

Object diagram showing same Player object, then before jerseyNumber = 7, then after jerseyNumber = 9.
SamePlayerObject.
  • New
  • Changed
  • Removed
State Develops as Statements Execute

Consider:

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:

player1.jerseyNumber = 7;

you may observe:

Activity diagram showing before jerseyNumber = 0, then after jerseyNumber = 7.
BeforeJerseyNumber.
  • New
  • Changed
  • Removed

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:

team = reference to a Team object

Before the relationship is assigned:

team = null

After:

player1.team = team1;

the state changes:

team → team1

The object now participates in a relationship.

UML Object Diagrams Show State Snapshots

A UML object diagram might show:

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:

  • Which object is involved?
  • What state does it have now?
  • What state was expected?
  • Which statement changed that state?

This is often more precise than saying:

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.