Java Reference
In-Depth Information
Here, the keyword
protected
is a specifier that limits access to
finalize( )
. This and the
It is important to understand that
finalize( )
is called just before garbage collection. It
is not called when an object goes out of scope, for example. This means that you cannot
know when—or even if—
finalize( )
will be executed. For example, if your program ends
before garbage collection occurs,
finalize( )
will not execute. Therefore, it should be used
as a “backup” procedure to ensure the proper handling of some resource, or for special-use
applications, not as the means that your program uses in its normal operation. In short,
fi-
nalize( )
is a specialized method that is seldom needed by most programs.
Ask the Expert
Q
:
I know that C++ defines things called
destructors
, which are automatically ex-
ecuted when an object is destroyed. Is
finalize( )
similar to a destructor?
A
:
Java does not have destructors. Although it is true that the
finalize( )
method approx-
imates the function of a destructor, it is not the same. For example, a C++ destructor
is always called just before an object goes out of scope, but you can't know when
fi-
nalize( )
will be called for any specific object. Frankly, because of Java's use of
garbage collection, there is little need for a destructor.
Try This 4-2
Demonstrate Garbage Collection and Finalization