1.7.1 Passing an Object Reference as an Argument

Arguments and Parameters Have Different Roles

An argument appears in a method call. A parameter is a variable declared by the method. The argument supplies the value that the parameter receives.

Caller invokes Game with Player as an argument, while Game receives the call.
Initial relationship
  • New
  • Changed
  • Removed
A Class Argument Supplies a Reference

Consider the call:

game.GetPlayerName(player);

Here `player` is the argument. In `GetPlayerName(Player selectedPlayer)`, the parameter `selectedPlayer` receives a copy of the reference stored in `player`. Both paths reach the same Player during the call.

The Receiver Is Separate from the Argument

The Game named `game` receives `GetPlayerName`; the Player named `player` is passed into that call. Inside the Game method, `this` refers to the Game, while `selectedPlayer` refers to the Player.

Caller argument and method parameter both lead to one Player named Jordan.
How the relationship changes
  • New
  • Changed
  • Removed
A Parameter Can Read the Passed Object

The Game method might return `selectedPlayer.Name`. That field read comes from the Player provided by the caller. The method can use another Player on a later call without changing its definition.

The Reference Value Is Copied

The parameter has its own variable slot. Copying the reference into that slot does not copy the object it identifies. The object remains available through the caller's `player` reference after the method returns.