The final keyword in java is used to restrict the user. The java final keyword can be used in many context. The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword. Final can be:

·        final variable

·        final method

·        final class 

1.     final variable-: If you use final keyword with variable then we cannot change value of final variable. For example


class Sample {
     final int maxValue = 20;
     public static void setValue(int mValue) {
          maxValue = mValue;
     public static void main(String args[]) {

 Output-: Compile Time Error

It will be show complete time error because we cannot set value in final variable.

2.     final method-: If you use final keyword with method then this method is final method and we can’t override final method in java

For example-:

class Sample1 {
     public final void setValue(int mValue) {
          System.out.print("Value is-: " + mValue);
class Sample2 extends Sample1 {
     public void setValue(int data) {
          System.out.print("Value is-: " + data);
class MainClass{
     public static void main(String args[]) {
          Sample2 sample2=new Sample2();

Output-: Compile Time Error 

3.  final class -: If we are using final keyword with class then we can extends this

class. For example


final class XYZ{  
class ABC extends XYZ{ 
   void demo(){
      System.out.println("My Method");
   public static void main(String args[]){ 
      ABC obj= new ABC();

Points to remember before use final

1.      A constructor cannot be declared as final.

2.      Local final variable must be initializing during declaration.

3.      All variables declared in an interface are by default final.

4.      We cannot change the value of a final variable.

5.      A final method cannot be overridden.

6.      A final class not be inherited.

7.      final, finally and finalize are three different terms. finally is used in exception handling and finalize is a method that is called by JVM during garbage collection.


  Modified On Dec-05-2017 02:19:38 AM

Leave Comment