Final (Java)

This is an old revision of this page, as edited by Chetandandgey (talk | contribs) at 16:59, 9 August 2005. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Final keyword is used in severl different contexts as a modifier meaning that what it modifies cannot be changed in any sense.

Final classes:

    For example,

    class Sample
     {
        ----
        ----
     }

This means that this class will not be subclassed.It provides benfit for security and thread safety.

String class is defined final to prevent creating a subclass. If you try to access the class(which is declared as final class) , then you will get a compiler error.


Final Method:

 You can use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.

For example, the object class has some methods as final and some are not.

Final Fields:

  When a field is declared final, it is treated as a constant. and cannot be changed.

If you try to change the value,then, compile time error or an exception is generated.

For example:

 class Myclass
 {
   final int n=10;
 }
 class My
 {
   public static void main(String args[])
    {
       Myclass m = new Myclass();
       System.out.println("Constant value is "+m.n);
    }
 }