Java Reference
In-Depth Information
initialize itself. Therefore, it is always a good idea to pass constructor methods up the
hierarchy to make sure that everything is set up correctly.
Finalizer Methods
Finalizer methods are almost the opposite of constructor methods. A constructor method
is used to initialize an object, and finalizer methods are called just before the object is
removed by the garbage collector, freeing up the memory for use.
The finalizer method is finalize() . The Object class defines a default finalizer method
that does nothing. To create a finalizer method for your own classes, override the final-
ize() method using this signature:
protected void finalize() throws Throwable {
super.finalize();
}
NOTE
The throws Throwable part of this method definition refers to the
errors that might occur when this method is called. Errors in Java
are called exceptions ; you learn more about them on Day 7.
Include any cleaning up that you want to do for that object inside the body of that
finalize() method. In the method, you always should call super.finalize() to enable
your class's superclasses to finalize the object.
You can call the finalize() method yourself at any time; it's a method just like any
other. However, calling finalize() does not trigger an object to be garbage collected.
Only removing all references to an object causes it to be marked for deletion.
When you're optimizing a Java class, one of the ways to reduce its memory use is to
remove references to class and instance variables as soon as they are no longer needed.
To remove a reference, set it to null .
For example, if you have a class that uses a NamedPoint object in a variable called
mainPoint , you could free up that object for garbage collection with the following state-
ment:
mainPoint = null;
Finalizer methods are valuable for optimizing the removal of an object—for example, by
removing references to other objects. However, it's important to note that the time a
 
Search WWH ::




Custom Search