Saturday, July 2, 2016

Final,Finally and Finalize - Difference

Most of the time interviewer can ask difference between the Final, Finally and Finalize in Java. I will explain you each in detail.

Final(Modifier)

Final is a modifier applicable for classes ,methods and variables. 

If i declare a variable as Final then it will become constant we cannot perform reassignment for that variable.

If a method declared as Final in child class we cannot override that method in the child class.

If a Class declare as Final Class then we cannot extend that class it means we cannot create the child class for this Class.

Finally:

Finally is a block and always associated with Try Catch.
try
{

//Write Risky Code

}
Catch(X e)
{
// Handling code
}

Finally
{
// Clean up code
//for eg - Close the database
}

Finalize:(Method)
Finalize
{
//Clean up code
}


Lets try to explain this with example. when object is created then it has to be destroyed by garbage collector.But some object can have associated database connection etc so before destroying this object Garbage collector called the Finalize method to close the database connection.

Thanks...




No comments:

Post a Comment