Image

Java - Core Java - final keyword

final keyword

The final keyword in java is used to restrict the user. The final keyword can be

  • final variable
  • final method
  • final class
  • final variable

    final variables are the constants which cannot change the value of a final variable once it is initialized.

    Program to use of final variable
    class FinalDemo{  
       final int MAX=89;
       void me(){  
          MAX=110;
       }  
       public static void main(String args[]){  
          FinalDemo obj=new  FinalDemo();  
          obj.me();  
       }  
    }
    Output
    D:\javap>javac FinalDemo.java
    FinalDemo.java:4: error: cannot assign a value to final variable MAX
          MAX=110;
          ^
    1 error
    Here we got a compilation error because we tried to change the value of a final variable

    final method

    A final method cannot be overridden which means even though a subclass can call the final method of parent class but we cannot override it.

     
    class FinalMethod{  
       final void demo(){
          System.out.println("FinalMethod Class 
    Method");
       }  
    }  
             
    class ABC extends FinalMethod{  
       void demo(){
          System.out.println("ABC Class Method");
       }  
             
       public static void main(String args[]){  
          ABC obj= new ABC();  
          obj.demo();  
       }  
    }
    Output
    D:\javap>javac FinalMethod.java
    FinalMethod.java:8: error: demo() in ABC cannot override demo() in FinalMethod
       void demo(){
            ^
      overridden method is final

    final class

    A class is declared as final then this class cannot be inherited.

    final class A{  
    }  
             
    class B extends A{  
       void demo(){
          System.out.println("I am in A");
       }  
       public static void main(String args[]){  
          A obj= new A(); 
          obj.demo();
       }  
    }
    Output
    error: cannot inherit from final A
    pre>