开发者

finalize() method

开发者 https://www.devze.com 2023-03-09 10:28 出处:网络
I want to know why its neccessary to write this statement super.finalize() in the following code. protected void finalize() throws Throwable {

I want to know why its neccessary to write this statement super.finalize() in the following

code.

protected void finalize() throws Throwable {

 开发者_高级运维   try {

        close();

    } catch(Exception e) {

    }

    finally {

        super.finalize();


    }
}


You're overriding the finalize method and since you're doing this, you need to call the parents finalize method as well. Otherwise it's possible that it didn't close streams or other resources accordingly.

You don't have to call the object's finalize() method for sure, but it can produce really nasty bugs when you e.g. copy/paste code to another class or change the parent of the inheritance.

It is wrapped in the finally-block to make sure that it is always called, no matter what happens (e.g. an exception in the close() method).

You should also take a look at the Javadoc: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize


If close() throws an exception, then the superclass's finalizer would never be called without the finally clause. Although, if the superclass is just an Object then it really doesn't matter: according to docs, The finalize method of class Object performs no special action; it simply returns normally.

0

精彩评论

暂无评论...
验证码 换一张
取 消