Java Reference
In-Depth Information
2.8.2 Losing Access to an Object
Consider the following:
Part a = new Part("Air Filter", 8.75);
Part b = new Part("Ball Joint", 29.95);
Assume these statements create the situation shown in Figure 2-7 .
name: Air Filter
price: 8.75
name: Ball Joint
price: 29.95
3472
a
5768
b
Figure 2-7. After creation of two Part objects
Suppose we execute this statement:
a = b;
The situation changes to that shown in Figure 2-8 .
name:Air Filter
price:8.75
name:Ball Joint
price:29.95
5768
a
5768
b
Figure 2-8. After assigning b to a
Both a and b now have the same value, 5768 . They both point to the Ball Joint object. In effect, when we change
the value of a , we lose access to the Air Filter object. When no variable points to an object, the object is inaccessible
and cannot be used. The storage occupied by the object will be garbage collected by the system and returned to the
pool of available storage. This takes place automatically without any action on the part of the program.
However, suppose we had written this:
c = a; // c holds 3472, address of "Air Filter"
a = b; // a, b hold 5768, address of "Ball Joint"
Now, we would still have access to Air Filter via c .
 
 
Search WWH ::




Custom Search