Objects and Classes in Java |
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 itsfinalize
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:Theprotected void finalize() throws ThrowableStack
class creates aVector
when it's created. To be complete and well-behaved, theStack
class should release its reference to theVector
. Here's thefinalize
method for theStack
class:Theprotected void finalize() throws Throwable { items = null; super.finalize(); }finalize
method is declared in theObject
class. As a result, 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.The last line of
Stack
's finalize method calls the superclass'sfinalize
method. Doing this cleans up any resources that the object may have unknowingly obtained through methods inherited from the superclass.
Objects and Classes in Java |