+ 2
Why are they no destructors in Java??
There are constructors and destructors in c++ There are constructors in Java to initialise the data But why are they no destructors!!
3 Answers
+ 7
Destructor is not possible because java is garbage collected language. We cannot predict when an object is destroyed. Finalize is used which is inherited method.
+ 2
The main goal of destructors, in languages that have them, is to release the memory used by the various components of the object you're currently destructing, which you're doing to free its own memory.
Java doesn't need that because it uses garbage collection : the memory used up by objects is released automatically when that object isn't used anymore. Therefore, so are the components of that object (Java garbage collection can detect circular trees of objects that are connected to each other, but not connected anymore to the rest of the program.)
However, that is the *main* goal of destructors. Another goal, is to release the other resources held by the object, besides the memory it relies in. For example, when reading a file, an object will hold a file descriptor that keeps this file in an open state with regards to the operating system. Operating systems can't deal with a program that keep millions of files open without ever releasing them, so it is important to release these handles. And destructors do that.
Java *does* have an equivalent to it. It's just not called a destructor as it doesn't do all the same things as classic destructors do. When you make an object that needs to release its resource, make it implement AutoCloseable. And when you're done with this object, never forget to call its close() method. Java provides a construct to automatically close AutoCloseable objects so that you don't forget to. It's called a try-with-resource. Looks like:
try(ResourceHolder holder = openMyResource()) {
// here you can use variable holder
}
// when you reach this point, Java will have called holder.close() no matter what happens, and variable holder doesn't exist anymore
0
You can read more here
https://www.geeksforgeeks.org/garbage-collection-java/