12/29/11

The final keyword in Java

Like other keywords in java, final is also a keyword used in several different contexts to define an entity which cannot later be changed.

Here in this tutorial we will be dealing with final classes, final methods, final variables and also I will be covering blank final variables.

Final Classes


The Java Programming language  permits us to apply the keyword final to classes. If the class is made final then it cannot be sub-classed. 

Ex :

The java.lang.String is a final class. This is done for security reasons, because it ensures that if the method is referenced as String then the method is a definite string of class String and not a string of class which has sub-classed String class.

Final Methods


Like class we can also mark methods as final. Methods that are marked as final cannot be overridden in any case. For security reasons only you must make the method as final if the method has implementation which you don't want others to change. 

Methods declared as final can be optimized. The compiler can generate a code that causes a direct call to the method, rather than invoking it the usual way i.e during the run-time.

Final Variables


If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.



NOTE :
             If you mark variable of a reference type as final, that variable cannot refer to any other object. However, you can change the object's contents, because only the reference itself is final.



Blank Final Variables


A blank final variable is a variable that is not initialized during its declaration. The initialization is delayed. A blank final instance variable must be assigned in a constructor, but it can be set only once. A blank final variable that is local variable can be set at any time in the body of the method, but it can be set only once.

The following code fragment is an example of how a blank final variable can be used in class.

public class Customer{
   private final long customerID;

   public Customer(){
      customerID = createID();
   }

   public long getID(){
      return customerID;
   }

   public long createID(){
      return ... // generates new ID
   }
   ... // more declarations
}



SHARE THIS POST: