What is the difference between ‘final’ method, class and variable in Java? Explained with example.

 Java’s final keyword is a modifier that can be applied to classes, methods, and variables. When applied to a class, it means that the class cannot be subclassed. When applied to a method, it means that the method cannot be overridden in a subclass. When applied to a variable, it means that the variable’s value cannot be changed once it is assigned.

Using the final keyword can be beneficial in certain situations, as it can make your code more robust and less prone to errors. In this blog post, we’ll take a look at how to use the final keyword in Java and see some examples of its use.

Classes

When applied to a class, final means that the class cannot be subclassed. This can be useful if you want to ensure that a class is always used in the same way and that its behavior cannot be changed.


final class MyClass {
    // code here
}

class Subclass extends MyClass { // Compile-time error
    // code here
}

Methods

When applied to a method, final means that the method cannot be overridden in a subclass. This can be useful if you want to ensure that a method always behaves in the same way, regardless of the subclass that is calling it.


class MyClass {
    final void myMethod() {
        // code here
    }
}

class Subclass extends MyClass {
    void myMethod() { // Compile-time error
        // code here
    }
}

Variables

When applied to a variable, final means that the variable’s value cannot be changed once it is assigned. This can be useful if you want to ensure that a variable always has the same value, regardless of the code that is executed.


final int myVariable = 5;
myVariable = 10; // Compile-time error

In addition to the above examples, final variables can also be used for constants in a class


class MyClass {
    static final int MAX_COUNT = 100;
}

Final keyword is a powerful tool that can be used to make your code more robust and less prone to errors. It can be applied to classes, methods, and variables to ensure that their behavior cannot be changed. By using final keyword, you can ensure that the classes, methods, and variables always behave in the same way, regardless of the code that is executed.