Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA PROGRAMMING

Constructor and Finalize method

 Providing Constructors for Your Classes 

All Java classes have constructors that are used to initialize a new object of that type. A constructor has the same name as the class.  


public Box() {

//body of constructor

}

Java supports name overloading for constructors so that a class can have any number of constructors, all of which have the same name.  

 Providing finalize() method for Your Class

Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply "letting go" of an object once you're done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very special and unusual case. Suppose your object allocates "special" memory without using new. The garbage collector knows only how to release memory allocated with new, so it won't know how to release the object's "special" memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here's how it's supposed to work. When the garbage collector is ready to release the storage used for your object, it 

You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it?

A point to remember is:
Garbage collection is only about memory.
That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. 

A Sample Code using Constructor and Finalize methods






Previous

Next