Saturday, 18 August 2012

Java: Understanding Final, Finally & Finalize

Yet another interesting topic which confuses most of us when asked all of a sudden, so here I present a most concise way of presenting all these 3 topics side by side in order to get a good grip on them.


Final:- It is used in the following three cases:
  1. If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
  2. If a method is marked as final then the method cannot be overridden by any other method.
  3. If a class is marked as final then this class cannot be inherited by any other class.
Finally:- If an exception is thrown in try block then the control directly passes to the catch block without executing the lines of code written in the remainder section of the try block. In case of an exception we may need to clean up some objects that we created. If we do the clean-up in try block, they may not be executed in case of an exception. Thus finally block is used which contains the code for clean-up and is always executed after the try ...catch block.

Finalize:- It is a method present in a class which is called before any of its object is reclaimed by the garbage collector. Finalize() method is used for performing code clean-up before the object is reclaimed by the garbage collector.

Garbage Collection Certification - finalize()

    protected void finalize() throws Throwable {}
  • every class inherits the finalize() method from java.lang.Object
  • the method is called by the garbage collector when it determines no more references to the object exist
  • the Object finalize method performs no actions but it may be overridden by any class
  • normally it should be overridden to clean-up non-Java resources ie closing a file
  • if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize(). This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling class
protected void finalize() throws Throwable {
    try {
        close();        // close open files
    } finally {
        super.finalize();
    }
}
  • any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
  • finalize() is never run more than once on any object 

0 comments:

Post a Comment