Java Reference
In-Depth Information
The lifetime of an object is determined by the variable that holds the reference to it — assuming there is
only one. If you have the declaration
Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0); // Create a sphere
then the Sphere object that the variable ball refers to dies when the variable ball goes out of scope, which
is at the end of the block containing this declaration. Where an instance variable is the only one referencing
an object, the object survives as long as the instance variable owning the object survives.
NOTE A slight complication can arise with objects, though. As you have seen, several vari-
ables can reference a single object. In this case, the object survives as long as a variable still
exists somewhere that references the object.
As you have seen before, you can reset a variable to refer to nothing by setting its value to null . If you
write the statement
ball = null;
the variable ball no longer refers to an object, and assuming there is no other variable referencing it, the
Sphere object that it originally referenced is destroyed. Note that while the object has been discarded, the
variable ball still continues to exist and you can use it to store a reference to another Sphere object. The
lifetime of an object is determined by whether any variable anywhere in the program still references it.
The process of disposing of dead objects is called garbage collection . Garbage collection is automatic in
Java, but this doesn't necessarily mean that objects disappear from memory straight away. It can be some
time after the object becomes inaccessible to your program. This won't affect your program directly in any
way. It just means you can't rely on memory occupied by an object that is done with being available imme-
diately. For the most part it doesn't matter; the only circumstances where it might be is if your objects were
very large, millions of bytes, say, or you were creating and getting rid of very large numbers of objects. In
this case, if you are experiencing problems you can try to call the static gc() method that is defined in the
System class to encourage the Java Virtual Machine (JVM) to do some garbage collecting and recover the
memory that the objects occupy:
System.gc();
This is a best efforts deal on the part of the JVM. When the gc() method returns, the JVM has tried
to reclaim the space occupied by discarded objects, but there's no guarantee that it has all been recovered.
There's also the possibility that calling the gc() method may make things worse. If the garbage collector is
executing some preparations for recovering memory, your call undoes that and in this way slows things up.
DEFINING AND USING A CLASS
To put what you know about classes to use, you can use the Sphere class in an example.
Search WWH ::




Custom Search