Hi Kavita,
Your question
What is correct?
1.A class extending a class having a finalize() method MUST write a finalize that calls super.finalize().
OR
2.We can do without writing the finalize() method.
OR
3.We can override the finalize() method of our super class
Options 2 and 3 are correct.
Option 1 is wrong because of
word MUST.
Normally called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. This is normal method so we don�t having chaining of finalize() method like constructors. You can call super.finalize() but it is not MUST
Option 2 is correct because
JVM is not enforcing any rule that finalize method has to performs some special action; it simply used to perform cleanup actions before the object is irrevocably discarded. If object is not having finalize method then it will get one from �Object� which performs no special action; it simply returns normally.
Option 3 is correct because
finalize()is a protected instance method of Object class. There is nothing special about it. As you can override any protected methods in subclass, you can override this method too. Remember it is protected so you can�t override with private modifier. It also throws Throwable object. The
Java programming language does not guarantee which
thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates. Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.
The finalize method is never invoked more than once by a Java virtual machine for any given object.
Regards
Vinod