Java final Keyword


The final keyword in Java is used to define constants, prevent method overriding, and restrict class inheritance. It is a versatile keyword that can be applied to variables, methods, and classes to enforce certain restrictions in your code. In this guide, we will explore the different uses of the final keyword and how it helps in writing more efficient and secure code.

Table of Contents

  1. What is the final Keyword?
  2. Uses of the final Keyword
  3. Benefits of Using the final Keyword
  4. Common Mistakes with the final Keyword

What is the final Keyword?

The final keyword in Java is used to define constants, prevent method overriding, and restrict inheritance. It is used to mark entities that should not be changed or modified after they are initialized or defined.

You can apply final to:

  • Variables: To create constants.
  • Methods: To prevent method overriding.
  • Classes: To prevent inheritance.

Uses of the final Keyword

Final Variables

When a variable is declared as final, its value cannot be changed once it has been initialized. This is commonly used to create constants, ensuring that the value of the variable remains unchanged throughout the program.

Example: Final Variable

public class Car {
    final String model = "Tesla";  // Final variable (constant)

    public void changeModel() {
        // model = "BMW";  // Error: Cannot assign a value to final variable 'model'
    }
}

In the example above, the model variable is declared as final. Once its value is assigned, it cannot be modified. Any attempt to change the value of model will result in a compilation error.

Key Points:

  • final variables must be initialized once and only once.
  • final variables are typically used for constants, especially when the value should not change.

Final Methods

When a method is declared as final, it cannot be overridden by any subclass. This ensures that the method implementation remains unchanged, which can be important in scenarios where you want to enforce a specific behavior in subclasses.

Example: Final Method

public class Car {
    final void display() {
        System.out.println("Displaying the car model");
    }
}

public class ElectricCar extends Car {
    // Attempting to override the final method results in a compile-time error
    // void display() {  // Error: Cannot override the final method from Car
    //     System.out.println("Displaying the electric car model");
    // }
}

In this example, the display() method in the Car class is marked as final. Therefore, the subclass ElectricCar cannot override this method.

Key Points:

  • final methods cannot be overridden in subclasses.
  • Use final methods to ensure certain behaviors cannot be modified by subclasses.

Final Classes

A final class cannot be subclassed or extended. This is useful when you want to prevent inheritance from a class, ensuring that no other class can extend its functionality.

Example: Final Class

public final class Car {
    // Class content
}

// Attempting to extend a final class results in a compile-time error
// class ElectricCar extends Car {  // Error: Cannot subclass the final class 'Car'
//     // Class content
// }

In this example, the Car class is marked as final, so it cannot be extended by any other class, including ElectricCar. This is particularly useful for classes like utility classes (e.g., String or Math), where subclassing might introduce unexpected behaviors.

Key Points:

  • final classes cannot be subclassed.
  • Use final classes to prevent inheritance and maintain the integrity of the class.

Benefits of Using the final Keyword

  1. Immutability: By declaring variables as final, you can make them constant, ensuring that their values remain unchanged throughout the program.

  2. Prevention of Method Overriding: By marking methods as final, you can prevent subclasses from overriding them, which helps preserve functionality and avoid unexpected changes.

  3. Security: Using final classes and methods adds a layer of security by preventing subclasses from altering critical functionality, making the code more reliable and stable.

  4. Performance Optimization: Some compilers and JVM implementations can optimize code more effectively when it knows certain methods or variables are not subject to change (e.g., by caching values or optimizing method calls).


Common Mistakes with the final Keyword

  1. Trying to Change a final Variable: You cannot modify a final variable once it has been initialized. Attempting to do so will result in a compile-time error.

    final int MAX_SPEED = 120;
    MAX_SPEED = 150;  // Compile-time error: Cannot assign a value to final variable 'MAX_SPEED'
    
  2. Attempting to Override a final Method: You cannot override a method that is marked as final. If you try to do so, a compilation error will occur.
    public class ElectricCar extends Car {
        @Override
        public void display() {
            // Compile-time error: Cannot override the final method from Car
        }
    }