Friday, November 14, 2008

Final, Finally and Finalize

Here I would like to discuss about some Keywords of Core Java. Here I am going to give you the basic idea about these keywords. This question is frequently asked in the interviews in the earlier stage of Career. Ok let's get into the business.

Final : Final is a keyword can be used in 3 scenarios. Firstly declare a class as Final as given below.

"public final class Test " If you declare a class like this that means you can not extend this class. That means "public class TestTwo extends Test" will NOT compile.
Second, You can declare method as final. If you declare a method final, you can't override the Final method in your subclasses. what if you do overload the final method. Yes, you can over load the final method.
Lastly, if the Final variable is declared you can not change the value of this. This indirectly means once you assign the value to any Final variable you can not change or modify the value of it. Generally these final variables are used while declaring constants with the combination of Static, Eg : PI value.

Finally : Finally is a block used in Exception handling. We all know about try and catch blocks where we put the statements where error could occur in try block and and we catch the exceptions in the catch block by passing the Exception object as argument. after all catch blocks you can put this Finally block. This will be executed in either case of exception. So, you can put the mandatory closing statements of files or connections you opened in the beginning.

Finalize() : Finalize is a method of class java.lang.object. This has to be overridden in the class you want according to your requirement. This method will be executed before the object get garbage collected. So, this would be executed when there will be no reference remain for the object.
protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}

No comments: