Java Keyword


Java final keyword is used to restrict the user.
We can create the following as final:-

1. variable

2. method

3. class

Note: We cannot declare a constructor as final because a constructor cannot be inherited.


final Variable


Java final variable is used to create a variable as constant i.e. value of a final variable cannot be changed.

If a final variable is not initialised at its declaration, then it can only be initialised in the constructor.

If we try to change the value of a variable declared as final then a compile time error will occur, as in the following example:


Example:

class Car
{
    // final variable
    final int speed=90;

    void run()
    {
        // Compile time error
        speed=50;
    }

    public static void main(String args[])
    {  
        Car c=new Car();
        c.run();
    }
}

final Method


Java final method can be inherited but it cannot be overridden.

If we try to override a final method then a compile time error will occur, as in the following example:


Example:

class Hero
{  
    final void run()
    {
        System.out.println("Hero is running"); //final method
    }
}

class Activa extends Hero
{  
    void run()
    {
        System.out.println("Activa is running");
    }

    public static void main(String args[])
    {  
        Activa a= new Activa();

        // Compile time error
        a.run();
    }
}

final class


A java final class cannot be extended. If we try to extend a final class then a compile time error will occur, as in the following example:


Example:

class Hero {}

class Activa extends Hero
{
    // Compile time error
    void run()
    {
        System.out.println("Activa is running");
    }

    public static void main(String args[])
    {
        Activa a= new Activa();  
        a.run();
    }
}