Objects, Classes, and Interfaces |
Before an object is garbage collected, the runtime system calls itsfinalize
method. The intent is forfinalize
to release system resources such as open files or open sockets before getting collected.Your class can provide for its finalization simply by defining and implementing a method in your class named
finalize
. Yourfinalize
method must be declared as follows:This class opens a file when it is constructed:protected void finalize() throws ThrowableTo be well behaved, theclass OpenAFile { FileInputStream aFile = null; OpenAFile(String filename) { try { aFile = new FileInputStream(filename); } catch (java.io.FileNotFoundException e) { System.err.println("Could not open file " + filename); } } }OpenAFile
class should close the file when it is finalized. Here's thefinalize
method for theOpenAFile
class:Theprotected void finalize () throws Throwable { if (aFile != null) { aFile.close(); aFile = null; } }finalize
method is declared in thejava.lang.Object
class. Thus when you write afinalize
method for your class you are overriding the one in your superclass. Overriding Methods talks more about how to override methods.If your class's superclass has a
finalize
method, then your class'sfinalize
method should probably call the superclass'sfinalize
method after it has performed any of its clean up duties. This cleans up any resources the object may have unknowingly obtained through methods inherited from the superclass.protected void finalize() throws Throwable { . . . // clean up code for this class here . . . super.finalize(); }
Objects, Classes, and Interfaces |