O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The finalize( ) Method

It is possible to define a method that will be called just before an object’s final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly. For example, you might use finalize( ) to make sure that an open file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java run-time system calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form:

Here, the keyword protected is a specifier that prevents access to finalize( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required