Sobes.tech
Junior

What is the keyword 'final'?

sobes.tech AI

Answer from AI

The final keyword in Java is used to denote an entity that cannot be changed or overridden.

Usage of final:

  1. Variables:

    • If a variable is declared as final, its value can only be assigned once.
    • When applied to primitive types, such a value becomes a constant.
    • When applied to reference types, the reference to the object cannot be changed. The object itself, to which the variable points (if mutable), can be modified.
    // Primitive type constant variable
    final int MAX_VALUE = 100;
    
    // final reference to a mutable object
    final List<String> names = new ArrayList<>();
    // names = new LinkedList<>(); // Compilation error: cannot reassign the reference
    names.add("Alice"); // Allowed: the contents of the object referenced by the final variable can be modified
    
  2. Methods:

    • If a method is declared as final, it cannot be overridden in subclasses. This is used to prevent unwanted behavior changes in inheriting classes or for optimization.
    class Base {
        final void doSomething() {
            // method implementation
        }
    }
    
    class Derived extends Base {
        // Compilation error: cannot override final method
        // @Override
        // void doSomething() {
        //     // new implementation
        // }
    }
    
  3. Classes:

    • If a class is declared as final, it cannot have subclasses, i.e., it cannot be inherited. This prevents extending the class and changing its behavior. An example of such a class is java.lang.String.
    final class ImmutableClass {
        // Fields and methods
    }
    
    // Compilation error: cannot inherit from a final class
    // class AnotherClass extends ImmutableClass {
    //     // ...
    // }
    

Using final helps to:

  • Improve security by preventing value changes or behavior overrides.
  • Increase performance in some cases (the compiler can apply optimizations).
  • Improve code readability by clearly indicating which elements are not intended for modification or extension.