Java Reference
In-Depth Information
myCar
8192
9216
model
Unknown
year
2000
9216
price
0.0
10240
xyCar
9216
Figure 6-17.
Memory state showing myCar and xyCar referencing the same Car object in memory
At this time, you can use reference variables
myCar
or
xyCar
to access the
Car
object in memory. The following
snippet of code will access the same object in memory:
myCar.model = "Civic LX"; /* Use myCar to change model */
myCar.year = 1999; /* Use myCar to change year */
xyCar.price = 16000.00; /* Use xyCar to change the price */
After executing the above three statements,
model
,
year
, and
price
will be changed for the
Car
object and the
memory state will look as shown in Figure
6-18
.
8192
myCar
9216
model
Civic LX
year
1999
9216
price
16000.0
xyCar
10240
9216
Figure 6-18.
Memory state showing myCar and xyCar referencing the same Car object in memory after myCar and
xyCar have been used to change the state of the Car object
At this point, two reference variables
myCar
and
xyCar
and one
Car
object exist in memory. Both reference
variables are referencing the same
Car
object. Let's execute the following statement and label it as #5:
myCar = new Car(); /* #5 */
The above statement will create a new
Car
object in memory with initial values for its instance variables and
assign the reference of the new
Car
object to the
myCar
reference variable. The
xyCar
reference variable still references
the
Car
object it was referencing before. Suppose the new
Car
object has been allocated at memory address
5120
. The
memory state for two reference variables
myCar
and
xyCar
and two
Car
objects is shown in Figure
6-19
.