The aim of destructor in any OOPs language is:
- Free up the memory (c++ suffer from memory allocation / deallocation)
- Clean up any other resources (like closing of open file stream)
Java take cares of all and hence there is no destructor in Java. (With the help of Garbage collection)
but still if you want to perform some additional tasks, then you can use the finalize() method of java.
But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program. A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory. The programmer should call this method at the approppriate place in the program. That is the only way to make sure your program works correctly.
Example code of finalize in java:
class Thing { public static int number_of_things = 0; public String what; public Thing (String what) { this.what = what; number_of_things++; } protected void finalize () { number_of_things--; } } public class TestDestructor { public static void main(String[] args) { Thing obj = new Thing("Test App"); } }
Leave a Reply to JscooterCancel reply