Mark As Completed Discussion

Destructors

Destructors are the exact opposite of constructor methods. They are automatically called when an object goes out of scope or when you forcefully delete an object.

It is difficult for a programmer to forcefully delete an object using a language with a garbage collector. Since Java is a garbage-collected language, you cannot predict when (or even if) an object will be destroyed. Hence, there is no direct equivalent of a destructor in Java.

According to a popular question on stackoverflow.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

The reason for this is that all Java objects are heap-allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator), there is no sensible way to implement real destructors. You will have a chance to peek at an example of an OOP language with a destructor in C++. See the code below for the previously implemented MyClass class:

TEXT/X-C++SRC
1class MyClass {
2public:
3    int* array;
4
5    // default constructor
6    MyClass() {
7        this->value = new int[5];
8        for(int i = 1; i <= 5; i++) {
9            this->value[i] = i;
10        }
11    }
12
13    // Destructor
14    ~MyClass() {
15        delete [] this->array;
16    }
17}