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

前端 未结 9 1266
旧时难觅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:15

    I think the reason why finalize is protected would be that maybe it's overridden by some classes in the JDK, and those overridden methods are called by JVM.

    0 讨论(0)
  • 2020-11-29 05:18

    The part about finalize() being called only once applies only to the calls from the GC. You can imagine the object as having a hidden flag "finalize() was called by the GC", and the GC checking that flag to know what to do with the object. The flag is not impacted in any way by your own handmade calls to finalize().

    On finalization, read this article from Hans Boehm (who is well-known for his work on garbage collection). This is an eye-opener about finalization; in particular, Boehm explains why finalization is necessarily asynchronous. A corollary is that while finalization is a powerful tool, it is very rarely the right tool for a given job.

    0 讨论(0)
  • 2020-11-29 05:19

    finalize() is only used by the JVM to clean up resources when the object is collected. It's reasonable for a class to define what actions should be taken on collection, for which it may need to access super.finalize(). It doesn't really make sense for an outside process to call finalize(), since an outside process doesn't have control over when the object is collected.

    0 讨论(0)
提交回复
热议问题