Page 282 - Introduction to Programming with Java: A Problem Solving Approach
P. 282
248 Chapter 7 Object-Oriented Programming—Additional Details 7.3 Assigning a Reference
The result of assigning one reference variable to another is that both reference variables then refer to the same object. Why do they refer to the same object? Since reference variables store addresses, you’re actu- ally assigning the right-side reference variable’s address into the left-side’s reference variable. So after the assignment, the two reference variables hold the same address, and that means they refer to the same object. With both reference variables referring to the same object, if the object is updated using one of the reference variables, then the other reference variable will benefit (or suffer) from that change when it attempts to ac- cess the object. Sometimes, that’s just what you want, but if it’s not, it can be disconcerting.
An Example
Suppose you want to create two Car objects that are the same except for their color. Your plan is to instanti- ate the first car, use it as a template when creating the second car, and then update the second car’s color instance variable. Will this code accomplish that?
Car johnCar = new Car();
Car stacyCar;
johnCar.setMake("Honda");
johnCar.setYear(2003);
johnCar.setColor("silver");
stacyCar = johnCar;
stacyCar.setColor("peach");
TheproblemwiththeabovecodeisthatthestacyCar = johnCar;statementcausesthetworefer- ences to point to the same single Car object. Figure 7.1a illustrates what we’re talking about.
Later, we’ll see that this aliasing (using different names for the same object) can be quite useful, but in this case, it’s not what we wanted. In the last statement in the code fragment above, when we use the setColor method to change Stacy’s car to “peach,” we’re not specifying the color for a new car. What we’re doing is repainting the original car. Figure 7.1a depicts the result. Uh oh . . . John may not be pleased to find his car repainted to peach!
This makes stacyCar refer to
the same object as johnCar. Apago PDF Enhancer
object
make
year
color
"Honda"
2003
"silver" "peach"
johnCar
stacyCar
Figure 7.1a Effect of assignment: stacyCar = johnCar; Both reference variables refer to exactly the same object.
If you want to make a copy of a reference variable, you should not assign the reference to another refer- ence. Instead, you should instantiate a new object for the second reference and then assign the two objects’ instance variables one at a time. Figure 7.1b shows what we’re talking about.