Local variables are not limited to:
int
double
bool
stringdouble
bool
stringA 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.
Consider:
Player newPlayer = new Player();PlayerThe local variable is designed to hold a reference to a Player object.
newPlayerThis name is available in the current method scope.
new Player()This creates the Player object.
=The new object reference is stored in the local variable.
Conceptually:
The local variable stores a reference that lets the method reach the object.
Suppose:
public void CreatePlayer()
{
Player newPlayer = new Player();
}The local variable:
newPlayerbelongs to the method scope.
Another unrelated method cannot simply use that local variable name.
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.
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.
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.
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.
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.
ClassType localName = new ClassType();Read it as: