你在一个子类中调用super.finalize()吗? [英] Do you call super.finalize() within a subclass?

查看:168
本文介绍了你在一个子类中调用super.finalize()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过(某处),当子类被垃圾收集时,不能保证父类的 c> finalize(),这是否意味着大多数开发人员重写 finalize()并调用 super.finalize()

解决方案

Finalize不会自动调用超类。所以,如果你重写finalize,确保超类清理的正确方法是
$ b $ pre $ protected void finalize(){
try {
//做子类清理
}
finally {
super.finalize();


$ / code>

请参阅这篇参考文章 http://www.ibm.com/developerworks/java/library/j-jtp06294/index。 html



值得注意的是,终结器并不是非常可预测的,你无法控制它们是否运行。在最终确定方法中不应该做任何关键的事情。一般来说,最好只是对班级进行显式清理。


I read (somewhere) that finalize() for a parent class is not guaranteed to be called when the subclass is garbage-collected, does this mean most developers override finalize() in the subclass and call super.finalize()?

解决方案

Finalize is not automatically called for the super class. So if you override finalize, the proper way to ensure the super class gets cleaned up would be

protected void finalize() {
    try {
       // do subclass cleanup
    }
    finally {
       super.finalize();
    }
}

See this reference article http://www.ibm.com/developerworks/java/library/j-jtp06294/index.html

It should be worth noting that finalizers are not very predictable and you don't have any control over if/when they run. Nothing critical should be done in finalize methods. In general it is better practice to just perform explicit cleanup of your class.

这篇关于你在一个子类中调用super.finalize()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆