by BehindJava

What is final keyword in java

Home » java » What is final keyword in java

In this tutorial we are going to learn about final keyword in java.

Final keyword can be used with the class, method and variable level, with respect to this final keyword stops inheritance at class level, stops method overriding at method level and stops value change i.e. makes a variable constant.

Immutable class can be created with the final keyword which means once an object is created, we cannot change its content.

Sample Code Snippet:

class FinalVariable
{
   public static void main(String[] args)
   {
      final int hours=24;
      System.out.println("Hours in 6 days = " + hours * 6);
   }
}

Output:
Hours in 6 days = 144

Points to Remember:

  • Constructors cannot be final.
  • If you make any class as a final then it cannot be inherited that means to stop inheritance make a class final.
  • If you make any data members as a final then it will become constant that means you cannot change value of this variable throughout the function.
  • If you make static data member of a class a final then it will become constant that means you cannot change the value of this variable throughout the class and it has to be initialized at class level.
  • If you make any non static data member of a class as a final then it will also become constant that means you cannot change the value of variable throughout the class and it has to be initialize at class level.
  • If you want to make any non static data member as a blank final variable then it has to be initialized via constructor only.
  • By default all the data members of an interface are final and static also.