BCA / B.Tech 9 min read

The `final` Keyword in Java

What is the `final` Keyword in Java?

The final keyword is a non-access modifier that can be applied to variables, methods, and classes. It is used to apply restrictions on these elements, essentially making them unchangeable in some way. Once declared as `final`, an entity cannot be modified, overridden, or inherited.

Applications of the `final` Keyword:
  1. Final Variable (Constant): When a variable is declared as `final`, its value cannot be changed once it has been initialized. It effectively becomes a constant.
    class Circle {
        final double PI = 3.14159; // This value can never be changed.
    
        double calculateArea(double radius) {
            // PI = 3.14; // This would cause a compile-time error.
            return PI * radius * radius;
        }
    }
  2. Final Method (Prevent Overriding): When a method is declared as `final`, it cannot be overridden by a subclass. This is used to enforce a specific implementation and prevent subclasses from altering it.
    class Vehicle {
        final void displayInfo() {
            System.out.println("This is a vehicle.");
        }
    }
    
    class Car extends Vehicle {
        // void displayInfo() { ... } // Compile-time error: Cannot override the final method.
    }
  3. Final Class (Prevent Inheritance): When a class is declared as `final`, it cannot be extended or inherited by any other class. This is often done for security and immutability, as seen in core Java classes like `String` and `Integer`.
    final class SecureData {
        // ... class members
    }
    
    // class ExtendedSecureData extends SecureData { ... } // Compile-time error: Cannot inherit from final class.