Page 283 - Introduction to Programming with Java: A Problem Solving Approach
P. 283
Figure 7.1b Effect of instantiating two separate objects and copying instance variable values from first object into instance variables of second object
To illustrate the strategy outlined in Figure 7.1b, we present the Car program in Figures 7.2 and 7.3. The code includes line numbers to facilitate tracing in an end-of-chapter exercise. Look at the makeCopy method in the Car class in Figure 7.2. As its name implies, that’s the method that’s in charge of making a copy of a Car object. The makeCopy method instantiates a new Car object and assigns its reference to a local variable named car. Then it copies each of the calling object’s instance variable values into car’s instance variables. Then it returns car to the calling module. By returning car, it returns a reference to the newly instantiated Car obAjecpt.ago PDF Enhancer
Now look at the driver in Figure 7.3. Note how main assigns makeCopy’s returned value to stacyCar. After stacyCar gets the reference to the newly created Car object, it calls setColor to change the Car object’s color. Since stacyCar and johnCar refer to two separate objects, the stacyCar.setColor("peach") method call updates only the stacyCar object, not the johnCar object. Yeah!
Whenever a method finishes, its parameters and locally declared variables are deleted. In our traces, we represent this deletion by drawing a heavy line under all of the terminating method’s parameters and local variables. In the makeCar method in Figure 7.2, there is one local variable, the reference variable, car. When the makeCar method finishes, the car reference variable is deleted. When a reference variable is deleted, the reference it holds is lost, and if that reference is not saved in a separate variable, the program will have no way of finding the object it referred to. In the makeCar method, the car reference variable’s value does get saved. It gets returned to main where it gets assigned to stacyCar.
Inaccessible Objects and Garbage Collection
Sometimes, you’ll want to instantiate a temporary object inside a method, use it for some purpose in that method, and then abandon that object when the method finishes. At other times you may wish to abandon an object before a method finishes. For example, suppose that in the main method in Figure 7.3, after call- ing makeCopy and creating a new Car object for stacyCar, you want to model John’s old car being destroyed in a fire and Stacy volunteering to let him become a co-owner of her new car. You could represent this joint ownership of one car with the statement:
johnCar = stacyCar;
7.3 Assigning a Reference 249
johnCar = newCar();
stacyCar = new Car();
<assign johnCar instance variables to stacyCar instance variables>
johnCar
stacyCar
make year
color
make year
color