0

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(); } } 
0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

May be it's not necessary: The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
Otherwise it's possible that the object will not be garbage collected at any time. this is not true at all, finalize is used to manage resources not part of the JVM, itself. The object will be GC 'd but any managed resource may not be.
@erickzetta not always neccessary, 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's better to just call it and be sure.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.