Java Reference
In-Depth Information
... a method in some class...
AClass ac, bc;
ac = new AClass ();
bc = new AClass ();
ac.j = 4; // Set j = 4inthe ac instance
bc.j = 40; // Set j = 40 in the bc instance
ac = bc; // Make ac a reference to the
// same object that bc references.
bc.j = 400; // Reset j in bc to 400.
int m = ac.j; // m now holds 400 since ac references the
// same object as bc and bc'sjvalue has
// been changed to 400.
...
The code first assigns values to the j variable in each object. Next we assign
ac to the same object that bc references with the ac = bc statement. So both
the ac and bc variables now reference the same object. Therefore, when we set
bc.j to the value 400 and then obtain the value of ac.j we get back 400 since
ac and bc both reference the same object in memory.
The object that was referenced by the original value of ac is no longer
available. The memory allocated for that object most likely still exists some-
where within the JVM's data buffers, but our code no longer has any way to
access that object. By assigning a new object to the ac variable we effectively
“orphaned” the original object that ac pointed to previously. When an object
is no longer referenced by any variables, the Java garbage collector eventually
reclaims the memory allocated for that object. See the Web Course Chapter 3:
Supplements section and also Chapter 24 for discussions of garbage collection in
Java.
3.6.2 Object references in method parameters
The argument, or parameter, list of a method can include object references. The
methods and data of that object can be accessed and modified by the method.
However, the reference itself passes by value. That is, the JVM makes a copy of
the internal memory reference and that copy goes into the parameter value. If
inside the method you set the reference variable to a new object, this will not affect
the reference variable in the calling method just like you cannot change primitive
values passed from calling methods. On the other hand, if you change the values
of the variables “inside” an object, then those changes apply to the object in the
calling method since both the calling method's reference variable and the called
method's reference variable refer to the exact same object.
 
Search WWH ::




Custom Search