Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Uses of keyword final in JAVA



Keyword " final " has three uses :

Use 1 : A variable can be declared as final, doing so prevents its contents from being modified. This means that we must initialize a final variable when it is declared.
For ex :
Final int a = 2 ;


The next two uses of Final apply to inheritance. 


Use 2Using Final to prevent overriding

While method overriding is one of the Java's most powerful feature, there will be times when we want to prevent it from occurring, to disallow a method from being overridden specify Final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.

class A
{      Final void math( )
        {
              System.out.println("This is a final method");
         }
}
class B extends A
{        void math( )         //illegal
          {       
                System.out.println("illegal"); 
           }
}



Use 3 : Using Final to prevent inheritance

Sometimes we want to prevent a class from being inherited. To do this precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final too.
As we expect it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

final class A
{    ......
      ........
      ........
}
class B extends A                    // illegal

}



Hope this helped.....


This post first appeared on Prepare For Interview And Recruitment Exams While, please read the originial post: here

Share the post

Uses of keyword final in JAVA

×

Subscribe to Prepare For Interview And Recruitment Exams While

Get updates delivered right to your inbox!

Thank you for your subscription

×