Explain Modifier Final

: Final can be applied to classes, methods and variables and the features cannot be

changed. Final class cannot be subclassed, methods cannot be overridden.

In Java, the final modifier is used to apply restrictions on classes, methods, and variables. Here’s a brief explanation of its usage in different contexts:

  1. Final Variables:
    • When applied to a variable, the final keyword ensures that the value of the variable cannot be changed once it has been assigned. It essentially makes the variable a constant.
    • Example:
      java
      final int MAX_VALUE = 100;
      // MAX_VALUE cannot be reassigned a new value
  2. Final Methods:
    • When applied to a method, the final keyword indicates that the method cannot be overridden by subclasses. It is a way to prevent further modification of a method in a subclass.
    • Example:
      java
      class Parent {
      final void display() {
      System.out.println("This method cannot be overridden.");
      }
      }
      class Child extends Parent {
      // Error: Cannot override the final method from Parent
      /*void display() {
      // Some implementation
      }*/

      }

  3. Final Classes:
    • When applied to a class, the final keyword indicates that the class cannot be subclassed. It ensures that no other class can extend it.
    • Example:
      java
      final class FinalClass {
      // Class members and methods
      }
      // Error: Cannot inherit from final class
      /*class SubClass extends FinalClass {
      // Some implementation
      }*/

In summary, the final modifier in Java is used to make variables, methods, and classes immutable or unmodifiable, depending on where it is applied.