1.4.14 Storing New Objects in Local Variables

A Local Variable Can Hold an Object Reference

Local variables are not limited to:

int
double
bool
stringdouble
bool
string

A local variable can also use a custom class type.

For example:

Player newPlayer = new Player();

This statement creates a new Player object and stores its reference in a local variable.

Read the Statement in Parts

Consider:

Player newPlayer = new Player();
Type
Player

The local variable is designed to hold a reference to a Player object.

Local variable name
newPlayer

This name is available in the current method scope.

Object creation
new Player()

This creates the Player object.

Assignment
=

The new object reference is stored in the local variable.

Picture the Runtime Relationship

Conceptually:

Class diagram showing newPlayer, then v, then Player object.
NewPlayer.
  • New
  • Changed
  • Removed

The local variable stores a reference that lets the method reach the object.

The Local Variable Exists Only in Its Scope

Suppose:

public void CreatePlayer()
{
    Player newPlayer = new Player();
}

The local variable:

newPlayer

belongs to the method scope.

Another unrelated method cannot simply use that local variable name.

The Object Can Be Configured Through the Local Variable

After:

Player newPlayer = new Player();

the method can access fields:

newPlayer.name = "Jordan";
newPlayer.jerseyNumber = 7;

The local variable provides access to the newly created object's state.

A Local Reference Can Be Assigned to an Object Field

Suppose Team contains:

public Player captain;

A method can create a Player locally:

Player newPlayer = new Player();

and later connect the Team to that object:

this.captain = newPlayer;

Now the field and local variable can both refer to that Player object.

Detailed shared-reference behavior is taught later in PC1.

For now, recognize that a compatible object reference can be stored in more than one reference location.

Do Not Confuse the Local Variable with a Field

Compare:

Player newPlayer = new Player();

inside a method with:

public Player captain;

inside a class.

newPlayer is local to method execution.

captain is part of object state.

Both can hold Player references, but they serve different roles.

A New Object Starts with Its Initial Field State

Immediately after:

Player newPlayer = new Player();

the object exists.

Its fields may still contain default values.

The method can then assign the state required by the design:

newPlayer.name = "Jordan";

Object creation and field assignment are separate operations.

Use Local Object Creation When the Method Needs a New Object

Do not create a new object merely because you need another variable name.

Use:

new Player()

when the design actually requires a distinct Player object.

If the method should use an existing Player, use the existing compatible reference instead.

The Main Pattern
ClassType localName = new ClassType();

Read it as: