- Objects are dynamically allocated by using the new operator.
- Let it know about how such objects are destroyed and their
memory is released for later reallocation.
- In some languages, such as c++, dynamically allocated
objects must be manually released by use of delete operator
Java takes a different approach:
- It handles deallocation for object automatically. The technique
that accomplishes this deallocation is called Garbage Collection.
- It works like this, when no references to an object exist,
that object assumed as to be no longer needed, and the memory occupied by the
object can be deleted.
- There is no explicit mechanism to destroy objects.
- Garbage collection only occurs if at all during the
execution of your program.
- There is one or more objects exist that are no longer
needed.
The finalize () method:
- Sometimes an object will need to perform some action when it
is destroyed.
- For example:- if an object is holding some non-java resources
such as file handling or window character font, then you might want to make
sure these resources are freed before an object is destroyed.
- To handle such situations, java provides a mechanism called
finalization.
- By using finalization, you can define actions that will occur,
when an object is just about to be destroyed by the garbage collector.
- To add finalize to a class, you simply define the finalize ()
method, you will specify those actions that must be performed before an object destroyed.
- The garbage collector runs periodically checking for object
that are no longer referenced by running state and at the same time the action
specified inside the finalize method is freed.
- The general form of finalize () method is
Protected void finalize ()
{
Finalization code here
}
- The keyword protected is a specified that prevents access to
finalize () by code defined outside its class.
- Finalize () is only called just prior to garbage collection
it is not called when an object is removed from memory.
- Therefore, the presence of finalize method provide the safe
environment to system resources, used by the object.
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.