blog

Home / DeveloperSection / Blogs / Final keyword in java

Final keyword in java

Simond Gear 2679 19-Jan-2017

Final keyword:-

It can be used to define final class, final method, final fields and final variable.

It can be used in many context in java. Final keyword perform a important role in java programming.

Its provide facility to change a variable into constant(final variable),whose value never changed.

Final class:- A Final class can not be inherited it means it can not have any child. It means if any class try

To inherit the property of this class, its can not allow to extend.

e.g.:-

final class AA
          {       
          }
           Class BB extends AA // Error because class AA is final
           {
          }

Final method:-

Fianl method can not be overridden, it means child class can not change algorithm of parent class final method. It means when child class extend the property of parent class, then its can not allow to change the algorithm of method of parent class in child class. When child class try to change the algorithm of parent class method, its generate error.

e.g:-
          class AA
          {
          Final void show()  // define final method in parent class
          {
            System.out.println(“Show method of parent class”);
           }
          Void disp() // define normal method in parent class
             {
            System.out.println(“disp method of parent class”);
             }
          }
And//
          Class BB extends AA// Extend property of Parent class
          {
          Void show()// Error because show method is final in parent class
             {
             System.out.println(“Show method of child class”);
            }     
          Void disp()//this method not generate error
             {
                   System.out.println(“disp method of child class”);
            }     
 
}

 

Final variable/final field:-

Value of final variable can not be change. It can only be Initialize. Assignment is not allowed. Initialization of final variable is mandatory. It means when we define final variable then its mandatory that’s we can initialize these variables, and the value of these variable can’t change and never assign another value, its acts like constant. its also know as constant. 

e.g:-

          class A
          {
          Final int x=10;//initialize final variable
          Final int y;
          Public A(int a)
            {
                   y=a;
            }
          Void show()
             {
                   X=90;//error because its final variable and its not allow to assign another value.
                   Y=60; //error because its final variable and its not allow to assign another value.
             }
          }

You can also visit these related articles and blogs

final keyword in Java

What is a final method in java

The final keyword: final classes and variables



Updated 17-Mar-2018

Leave Comment

Comments

Liked By