Monday, December 17, 2012

final, finally and finalize() in JAVA...

All the three keywords final, finally and finalize() plays a very important role in JAVA. Final is a keyword used for declaration of variable which cannot be edited, finally is a segment of code used for code cleanup in case of an exception whereas finalize is a method used for object cleanup before garbage collection.

Use of final, finally and finalize



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.

Examples of final, finally and finalize



1. final

With a variable

Code:
final int c=1;
With a method
Code:
class A 
{
    final void func()
    {
        System.out.println("Inside class A");
    }
}
class B extends A
{
    void func()     // Error, cannot override
    {
        ... 
    }
}
With a class
Code:
final class A 
{
    ...
}

class B extends class A{    //Error, cannot inherit

}
2. finally
Code:
class call
{
    static void callA()
    {
        try
        {
            System.out.println("callA");
            Throw new runtimeexception("demo"); 
            ...//clean-up code which is never reached because of exception
        }
        catch( Exception e) 
        {
            System.out.println("Exception caught");
        }
        finally
        {
            System.out.println("finally of callA");
            ...//clean-up code written here which is executed
        }
    }
}
3. finalize
Code:
public class MyClass
{
    protected void finalize()
    { 
        ... //code written here for clean-up

    }
}

No comments:

Post a Comment

Creating mirror of BST