Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces

The finalize() Method

Definition, Concept, Syntax | Interfaces

Java has a facility of automatic garbage collection. Hence even though we allocate the memory and then forget to deallocate it then the objects that are no longer is used get freed.

The finalize() method

• Java has a facility of automatic garbage collection. Hence even though we allocate the memory and then forget to deallocate it then the objects that are no longer is used get freed.

• Inside the finalize() method you will specify those actions that must be performed before an object is destroyed.

• The garbage collector runs periodically checking for objects that are no longer referenced by any running state or indirectly though other referenced objects.

• To add finalizer to a class simply define the finalize method. The syntax to finalize() the code is -

void finalize()

{

finalization code

}

Note that finalize() method is called just before the garbage collection. It is not called when object goes out-of –scope.

• The finalize method of an object is called when garbage collector is about to clean up the object.

• The purpose of finalization is to perform some action before the objects get cleaned up.

•  The clean up code can be kept in the finalize method block.

Review Question

1.State the purpose of finalize () method in java. With an example explain how finalize () method can be used in java program. 

Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : Definition, Concept, Syntax | Interfaces - The finalize() Method