Is there a destructor for Java?

前端 未结 22 1705
[愿得一人]
[愿得一人] 2020-11-22 11:47

Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?

To make my question m

22条回答
  •  梦谈多话
    2020-11-22 12:24

    Because 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.

    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).

    There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

提交回复
热议问题