Why is the finalize() method in java.lang.Object “protected”?

前端 未结 9 1288
旧时难觅i
旧时难觅i 2020-11-29 04:28

Out of curiosity,

Why is the finalize() method\'s access modifier is made as protected. Why cant it be public? Can someone exp

9条回答
  •  旧巷少年郎
    2020-11-29 05:00

    Also, I came to know that finalize() method is called only once. If i call it twice in my program, internally what is happening?

    You probably ask this under impression of C++ ~destructors. In java finalize () method doesn't do any magic (like clearing memory). It's supposed to be called by garbage collector. But not vice versa.

    I recommend you to read correspondent chapter in Joshua Bloch's "Effective Java". It says that using finalizers is a bad practice and can cause performance and other issues, and there are only several cases when they should be used. The chapter begins with next words:

    Finalizers are unpredictable, often dangerous, and generally unnecessary.

提交回复
热议问题