The “final” Keyword In Java​

The "final" Keyword In Java

The final keyword in Java is a non-access modifier that can be applied to variables, methods, and classes to restrict their behavior. It serves several important purposes, including:

1. Declaring Constants: When applied to a variable, the final keyword makes it a constant, meaning its value cannot be changed after it is initialized. This is useful for defining values that should remain consistent throughout the program, such as mathematical constants, configuration settings, or resource paths. 

For instance, declaring final double PI = 3.14159265358979323846; creates an immutable constant PI representing the value of pi. Let’s see another example:

				
					public class Constants {
    public static final int MAX_SIZE = 100;
    public final String name;

    public Constants(String name) {
        this.name = name;
    }
}

				
			

In the above example, MAX_SIZE is a class-level constant, and the name is an instance variable marked as final. Once initialized, attempting to change these values will result in a compilation error.

2. Final Methods: When a method is declared as final, it means that it cannot be overridden by any subclass. This is often used in the context of enforcing a specific behavior that should not be altered in derived classes. This is particularly useful for methods that represent core functionality or implement specific behavior that should not be modified by subclasses.

 In the below example, the displayMessage method in the Parent class is marked as final, preventing any subclass, like Child, from overriding it.

				
					public class Parent {
    public final void displayMessage() {
        System.out.println("This method cannot be overridden.");
    }
}

public class Child extends Parent {
    // Compilation error: Cannot override the final method
    // public void displayMessage() { }
}

				
			

3. Final Classes: When applied to a class, the final keyword prohibits other classes from inheriting from it. This means that the class cannot be extended, effectively making it the ultimate implementation of a concept.

This is useful for classes that represent fundamental data types or provide self-contained functionalities, ensuring that their behavior remains consistent and preventing unintended extensions. For instance, declaring the final class Integer {} prevents other classes from inheriting from the Integer class, which is the wrapper class for the primitive data type int.

				
					public final class FinalClass {
    // Class implementation
}

 public class SubClass extends FinalClass { }
// Compilation error: Cannot inherit from final class
				
			

4. Final Parameters: When a method parameter is marked as final, it ensures that the parameter is not modified within the method. This can be particularly useful for clarity and avoiding unintended side effects.

In the add method in the below example, attempting to modify the final parameters a or b will result in a compilation error.

				
					public class Calculator {
    public int add(final int a, final int b) {
        // Compilation error: Cannot assign a value to final variable 'a'
        // a = 10;

        return a + b;
    }
}

				
			

5. Final and Immutability: Combining ‘final‘ with immutable classes can lead to more robust and thread-safe code. Immutable objects are those whose state cannot be changed after construction, and using ‘final‘ can help enforce this immutability.

In the below example, By making the class final and ensuring all fields are final, we guarantee that once an object of ImmutableClass is created, its state cannot be altered.

				
					public final class ImmutableClass {
    private final int value;

    public ImmutableClass(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

				
			

Characteristics of Final Keyword:

  • Immutability: Final variables cannot be reassigned after initialization.

  • Inheritance Restriction: Final methods cannot be overridden by subclasses.

  • Extension Control: Final classes cannot be extended by other classes.

Usage Guidelines:

  • Use final for constants to ensure consistent values.

  • Use final for methods that represent core behavior and should not be modified.

  • Use final for classes where extension is not intended or would violate the concept’s integrity.

Benefits of Using Final Keyword:

  • Improved Code Readability: Clearly indicates immutable variables, preventing method overrides, and controlling class extension.

  • Enhanced Code Reliability: Ensures consistent values, protects core behavior, and prevents unintended class extensions.

  • Maintained Code Maintainability: Makes code easier to understand, modify, and update by limiting behavior changes.

Conclusion

The final keyword in Java is a versatile tool that contributes to code stability, security, and maintainability. By using the final appropriately, developers can convey their intentions clearly and prevent unintentional modifications to variables, methods, or classes. Whether it’s declaring constants, preventing method overrides, or ensuring immutability, mastering the final keyword is an essential skill for writing robust and reliable Java code.