Destroying Objects

From Wikibooks, open books for an open world
Jump to: navigation, search

Using Static Members Java Programming
Destroying Objects
Overloading Methods and Constructors
Navigate Classes and Objects topic: v  d  e )

Unlike in many other object-oriented programming languages, Java performs automatic garbage collection - any unreferenced objects are automatically erased from memory - and prohibits the user from manually destroying objects.

[edit] finalize()

When an object is garbage-collected, the programmer may want to manually perform cleanup, such as closing any open input/output streams. To accomplish this, the finalize() method is used. Note that finalize() should never be manually called, except to call a super class' finalize method from a derived class' finalize method. Also, we can not rely on when the finalize() method will be called. If the java application exits before the object is garbage-collected, the finalize() method may never be called.

Computer code
protected void finalize() throws Throwable
{
    try {
        doCleanup();        // Perform some cleanup.  If it fails for some reason, it is ignored.
    } finally {
        super.finalize(); // Call finalize on the parent object
    }
}


The garbage-collector thread runs in a lower priority than the other threads. If the application creates objects faster than the garbage-collector can claim back memory, the program can run out of memory.

The finalize method is required only if there are resources beyond the direct control of the Java Virtual Machine that need to be cleaned up. In particular, there is no need to explicitly close an OutputStream, since the OutputStream will close itself when it gets finalized. Instead, the finalize method is used to release either native or remote resources controlled by the class.

Clipboard

To do:
Add some exercises like the ones in Variables

Using Static Members Java Programming
Destroying Objects
Overloading Methods and Constructors