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.
Final:- It is used in the following three cases:
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.
1. final
With a variable
With a method
With a class
2. finally
3. finalize
NOTE:- finalize method is always protected so that it cannot be accessed from anywhere outside the class but can be accessed only from within the class and its subclasses.
Use of final, finally and finalize
Final:- It is used in the following three cases:
- If the final keyword is attached to a variable then the variable becomes constant i.e. its value cannot be changed in the program.
- If a method is marked as final then the method cannot be overridden by any other method.
- If a class is marked as final then this class cannot be inherited by any other class.
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;
Code:
class A
{
final void func()
{
System.out.println("Inside class A");
}
}
class B extends A
{
void func() // Error, cannot override
{
...
}
}
Code:
final class A
{
...
}
class B extends class A{ //Error, cannot inherit
}
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
}
}
}
Code:
public class MyClass
{
protected void finalize()
{
... //code written here for clean-up
}
}
