Final Keyword

Final keyword has multiple usage in java.

  • To make a constant

    Constant can be created using final keyword. A constant has to be defined at the time of declaration.

    Program :

    
    class on
    {
    public static void main(String arg[])
    {
    final double PI=3.14;
    System.out.println(PI);
    }
    }
    /*Output:
    3.14
    */

    In above program one double constant is created using final keyword.


  • To make a class non-inheritable

    if a class is declared with final keyword then this class can't be inherited by any other class.

    Program :

    
    final class A
    {
    }
    class B extends A // Error: Class A can't be inherited.
    {
    }


    Compilation of above program will give following error:

    Error B.java:4: error: cannot inherit from final A
    class B extends A // Error: Class A can't be inherited.
    ^
    1 error


  • To make a method Non-overridable

    If final keyword is used with method then that method become non-overridable. It means a method with final keyword in parent class can't be overridden in child class. Trying to override a final method generate an error.

    Program :

    
    class A 
    {
    final void show() {}
    }
    class B extends A
    {
    void show() // trying to override a final method : Error
    {
    }
    }

    Compilation of above program will give following error:

    Error two.java:7: error: show() in B cannot override show() in A
    void show() // trying to override a final method : Error
    ^
    overridden method is final
    1 error