Question:
In Java, how do I achieve the same functionality which is provided by
class destructors in C++? Is there a destructor method in Java?
Answer:
Java does not possess the concept of a destructor. In C++, you need
to perform explicity memory management, invoking new to allocate
memory and invoking delete to free memory. The C++ new operator creates
new objects and invokes their constructors as part of the
initialization process. Java works in much the same way. The delete
operator frees the memory used by an object, invoking its destructor
as part of the process. Java does not possess this feature. Instead,
Java frees memory for you on its own.
Java is a garbage collected language. This means that part of the
runtime system is dedicated to finding objects that are no longer
referenced by any part of a program and freeing up the memory.
Therefore, destructors are not needed.
The closest thing to a
destructor in the Java language is the finalize() method defined in
the Object class. The finalize() method of an object is invoked by
the garbage collector prior to freeing its memory. However, no
guarantees are made about which thread will invoke finalize() or exactly
when it will be invoked. The purpose of the finalize() method is to
allow objects to free resources that cannot be freed by the garbage
collector (usually native resources such as file descriptors and
graphics contexts). As a consequence, you normally only implement the
finalize() method when you are using native code in a class.