|
|
Objects and Classes in Java |
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 itsfinalizemethod 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
finalizemethod in your class. This method must be declared as follows:Theprotected void finalize() throws ThrowableStackclass creates aVectorwhen it's created. To be complete and well-behaved, theStackclass should release its reference to theVector. Here's thefinalizemethod for theStackclass:Theprotected void finalize() throws Throwable { items = null; super.finalize(); }finalizemethod is declared in theObjectclass. As a result, when you write afinalizemethod 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'sfinalizemethod. Doing this cleans up any resources that the object may have unknowingly obtained through methods inherited from the superclass.
|
|
Objects and Classes in Java |