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

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

    It's not public (or default access) because it's meant to be called by the JVM internally when the object is garbage collected - it's not meant to be called by anything else. And it's not private because it's meant to be overridden and you can't override private methods.

    If i call it twice in my program, internally what is happening? Will the garbage collector will call this again?

    Probably yes, but it's hard to imagine a scenario where this would make any kind of sense - the point of finalize() is to do cleanup when an object is garbage collected. And it doesn't even do that well, so it's really something you should avoid altogether rather than experiment with.

提交回复
热议问题