Final keyword In Java

In Java, the final keyword is used to declare a constant or to make a variable, method, or class unchangeable, which means once declared and initialized, its value or reference cannot be changed. The final keyword can be applied to variables, methods, and classes.


When a variable is declared as final, it can only be initialized once, either at the time of declaration or in a constructor. Any attempt to change the value of a final variable after initialization will result in a compile-time error.


Similarly, when a method is declared as final, it cannot be overridden in a subclass. This means that the behavior of the method is fixed and cannot be changed by any subclass. When a class is declared as final, it cannot be subclassed, which means that no other class can extend it.


Here are some examples that demonstrate the use of the final keyword in Java:


  1. 1. Final Variable:
  2. public class Main {
       public static void main(String[] args) {
          final int x = 5;
          // Attempting to change the value of x will result in a compile-time error
       }
    }


In this example, the variable x is declared as final, which means that it can only be initialized once. Any attempt to change the value of x will result in a compile-time error.


  1. 2. Final Method:
  2. class Animal {
       public final void makeSound() {
          System.out.println("Animal is making a sound");
       }
    }
    
    class Dog extends Animal {
       // Attempting to override the makeSound() method will result in a compile-time error
    }
    
    public class Main {
       public static void main(String[] args) {
          Dog dog = new Dog();
          dog.makeSound(); // Output: Animal is making a sound
       }
    }


In this example, the makeSound() method is declared as final in the Animal class, which means that it cannot be overridden in a subclass. Any attempt to override the makeSound() method in the Dog class will result in a compile-time error.


  1. 3. Final Class:
  2. final class Animal {
       // This class cannot be extended by any other class
    }
    
    class Dog extends Animal {
       // Attempting to extend the Animal class will result in a compile-time error
    }
    
    public class Main {
       public static void main(String[] args) {
          Dog dog = new Dog();
       }
    }


In this example, the Animal class is declared as final, which means that it cannot be extended by any other class. Any attempt to extend the Animal class in the Dog class will result in a compile-time error.