Difference between final, finally and finalize

Published by Manish Rawat on

final, finally and finalize in java

This is a very important question, which is asked frequently in java interview. firstly we will explain final.

final :- 
final is a modifier applicable for classes, methods and variables.
1. final with Class : if a class declared as final we can’t extend that class. i.e we can’t create child class for that class.
final class FinalExampleWithClass {
    public static void main(String[] args)
    {
        int a = 10;
    }
}
// here gets Compile time error that
// we can't extend FinalExampleWithClass because it is final class.
class AnyChildClass extends FinalExampleWithClass {
    // more code here with main method
}
2. final with Method : if a method  declared as final then we can’t override  that method in the child class.
class FinalExampleWithMethod {
    final void abc() {
       System.out.println("This is abc method");
    }
    public static void main(String[] args)
    {
    }
}
 
class MM extends FinalExampleWithMethod {
 
    // Here we get compile time error
    // we can't override this method because this method is defined as final.
    void abc() {}
}
3. final with Variables : if a variable declared as final then it will become constant and we can’t perform re-assignment for that variable.
class FinalExampleWithVariable {
public static void main(String[] args)
{
// Non final variable
int a = 5;

// final variable
final int b = 6;

// modifying the non final variable : Allowed
a=3;

// modifying the final variable :
// Immediately gives Compile Time error.
b=8;
}
}
finally :-
finally is a block always associate with try catch  to maintain cleanup code.
try
{
  //risky code...
}
catch(IOException e){
//handling code
}
finally{
//cleanup code
}
finalize :-
finalize is a method which is always invoked by garbage collector just before destroying an object to perform cleanup activities.
class FinalizeExample{
    public static void main(String[] args)
    {
        String s = new String("Arti");
        s = null;
 
        // Requesting JVM to call Garbage Collector method
        System.gc();
        System.out.println("Main Completes");
    }
 
    // Here overriding finalize method
    public void finalize()
    {
        System.out.println("finalize method overriden");
    }
}
node:- finally meant for cleanup activities related to try block. where as finalize() meant for cleanup activities related to object.
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *