final Keyword in Java

The final Keyword in Java

The final keyword in Java is used to restrict the usage of variables, methods, and classes. It serves as a form of protection, ensuring that certain aspects of your code remain unchanged, thereby improving the safety and predictability of your program. Understanding the final keyword is crucial for writing robust Java applications.

In this tutorial, we'll explore the different ways to use the final keyword in Java, along with examples to illustrate its application.


1. final with Variables

When you declare a variable as final, you cannot change its value once it has been initialized. This makes the variable a constant.

Syntax:

final dataType variableName = value;

Example:

public class FinalVariableExample {
    public static void main(String[] args) {
        final int MAX_VALUE = 100;
        System.out.println("MAX_VALUE: " + MAX_VALUE);

        // Uncommenting the following line will cause a compilation error
        // MAX_VALUE = 200;
    }
}

Explanation:

  • MAX_VALUE is declared as final, meaning its value cannot be changed once assigned.

  • Trying to reassign a value to MAX_VALUE will result in a compilation error.

Output:

MAX_VALUE: 100

2. final with Methods

When a method is declared as final, it cannot be overridden by subclasses. This is useful when you want to ensure that the method's behavior remains consistent across all subclasses.

Syntax:

final returnType methodName(parameters) {
    // method body
}

Example:

class ParentClass {
    final void show() {
        System.out.println("This is a final method.");
    }
}

class ChildClass extends ParentClass {
    // Uncommenting the following method will cause a compilation error
    // void show() {
    //     System.out.println("Attempting to override a final method.");
    // }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        ChildClass obj = new ChildClass();
        obj.show();
    }
}

Explanation:

  • The show method in ParentClass is marked as final, preventing it from being overridden in ChildClass.

  • Attempting to override the show method in the subclass will result in a compilation error.

Output:

This is a final method.

3. final with Classes

When a class is declared as final, it cannot be subclassed or inherited. This is useful when you want to prevent other classes from modifying the behavior of your class through inheritance.

Syntax:

final class ClassName {
    // class body
}

Example:

final class FinalClass {
    void display() {
        System.out.println("This is a final class.");
    }
}

// Uncommenting the following code will cause a compilation error
// class SubClass extends FinalClass {
// }

public class FinalClassExample {
    public static void main(String[] args) {
        FinalClass obj = new FinalClass();
        obj.display();
    }
}

Explanation:

  • FinalClass is declared as final, meaning no other class can extend it.

  • Attempting to create a subclass of FinalClass will result in a compilation error.

Output:

This is a final class.

4. final with Reference Variables

When you declare a reference variable (e.g., an object or an array) as final, you cannot reassign the reference to point to a different object. However, you can still modify the object's internal state (i.e., its fields or elements).

Example:

public class FinalReferenceExample {
    public static void main(String[] args) {
        final int[] numbers = {1, 2, 3, 4, 5};

        // Modifying the internal state of the array
        numbers[0] = 10;
        System.out.println("Modified first element: " + numbers[0]);

        // Uncommenting the following line will cause a compilation error
        // numbers = new int[]{6, 7, 8, 9, 10};
    }
}

Explanation:

  • The final keyword prevents the numbers array reference from pointing to a new array, but the elements of the array can still be modified.

  • Attempting to reassign the numbers reference will result in a compilation error.

Output:

Modified first element: 10

5. final and Constructors

The final keyword cannot be applied to constructors. Constructors are meant to initialize objects, and since they cannot be inherited or overridden, there is no need to mark them as final.

Example:

public class FinalConstructorExample {
    final int value;

    // Constructor to initialize the final variable
    FinalConstructorExample(int value) {
        this.value = value;
    }

    public static void main(String[] args) {
        FinalConstructorExample obj = new FinalConstructorExample(10);
        System.out.println("Value: " + obj.value);
    }
}

Explanation:

  • The final keyword is used to declare the value variable, which is initialized in the constructor.

  • Constructors cannot be marked as final.

Output:

Value: 10

6. Advantages of Using final

  1. Security: By using final, you can prevent accidental changes to variables, methods, or classes, ensuring that your code behaves as expected.

  2. Performance: The JVM can optimize final variables and methods, leading to better performance.

  3. Design Clarity: Declaring a method or class as final clearly communicates your intent that it should not be overridden or extended.


7. Common Use Cases for final

  1. Constants: Use final with variables to create constants that should not change throughout the program.

  2. Immutable Classes: Use final with classes to create immutable classes that cannot be subclassed.

  3. Preventing Method Overriding: Use final with methods to ensure that they cannot be overridden by subclasses, preserving the method’s original behavior.


Conclusion

The final keyword in Java is a powerful tool for creating constants, securing methods from being overridden, and preventing classes from being subclassed. By understanding and using the final keyword effectively, you can write more reliable and maintainable Java programs.

For more Java tutorials and resources, visit codeswithpankaj.com.

Last updated