Previous | Next | Trail Map | Learning the Java Language | Objects and Classes in Java

Writing a finalize Method

When all references to an object are dropped, the object is no longer required and becomes eligible for garbage collection. Before an object is garbage collected, the runtime system calls its finalize method to release system resources such as open files or open sockets before the object is collected.

Your class can provide for its finalization simply by defining and implementing a finalize method in your class. This method must be declared as follows:

protected void finalize() throws Throwable
The Stack class creates a Vector when it's created. To be complete and well-behaved, the Stack class should release its reference to the Vector. Here's the finalize method for the Stack class:
protected void finalize() throws Throwable {
    items = null;
    super.finalize();
}
The finalize method is declared in the Object class. As a result, when you write a finalize method for your class, you are overriding the one in your superclass. Overriding Methods talks more about how to override methods.

The last line of Stack's finalize method calls the superclass's finalize method. Doing this cleans up any resources that the object may have unknowingly obtained through methods inherited from the superclass.


Previous | Next | Trail Map | Learning the Java Language | Objects and Classes in Java