Page 285 - Introduction to Programming with Java: A Problem Solving Approach
P. 285

                Figure 7.3
CarDriver class that drives Car class in Figure 7.2
Doing this overlays johnCar’s previous reference to John’s original Car object, and that Car object be- comes inaccessible to the program (abandoned), like Car object #1 is in this picture:
johnCar Car object #1
7.3 Assigning a Reference 251
 1 /********************************************************
2 *
CarDriver.java
Dean & Dean
This class demonstrates copying an object.
6 ********************************************************/
3 *
4*
5 *
7
8 public class CarDriver
9{
10
public static void main(String[] args)
11
{
12
Car johnCar = new Car();
Car stacyCar;
johnCar.setMake("Honda");
johnCar.setYear(2003);
johnCar.setColor("silver");
stacyCar = johnCar.makeCopy();
stacyCar.setColor("peach");
System.out.println("John's car:");
johnCar.display();
System.out.println("Stacy's car:");
stacyCar.display();
    Apago PDF Enhancer
13
14
15
  16
17
 18
19
20
21
22
23
24
}
// end main
25
}
// end class CarDriver
Output:
John's car:
make= Honda
year= 2003
color= silver
Stacy's car:
make= Honda
year= 2003
color= peach
This assigns the returned reference to a reference variable in the calling method.
      stacyCar Car object #2
 




































   283   284   285   286   287