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( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access