Thursday, 13 October 2011

final Keyword


There are three uses of final:

(1)           To make the variable constant

The variable declared as a final cannot be changed. It is common coding convention to choose all uppercase identifiers for final variables.
final int ADD=1;
final string ST1=” This is Java “;

(2)           To prevent overriding of method

The method declared as a final cannot be overridden.
Ex,
class A
{
     final void add ()
     {
               System.out.println (“This is Final Method“);
     }
}
class B extends A
{
     void add ()             //error b’coz add is Final
     {
    
     }
}


(3)            To prevent Inheritance

The class declared as a final cannot be inherited means it has no derivatives. It is a standalone class.

Ex,
final class A
  {
           
  }
class B extends A      // error can’t be inherited
{
 
}

Posted by:Ruchita Pandya

No comments:

Post a Comment