In this post, we will discuss all things final in Java. Final Classes, Final Methods, Final Variables and finally Final Arguments.
Let us look at an example. We have a class A that is declared as final.
Now let us try to create a subclass of A
This will give a compilation error. The reason is that a final class cannot be subclassed. Once you subclass, you can potentially modify the public methods of the parent class. By declaring the class as final, you as a developer ensure that no unwarranted effects take place with respect to your code.
Some popular classes in the Java library that are declared as final are String, Integer, Boolean.
Now if we make the method in the super class as final
This gives a compilation error. The final method cannot be overridden.
You can assign the value to a variable any number of times. However, when you declare the variable as final, it can be assigned the value only once. If you try to assign a value to the variable a second time, it will throw a compilation error.
The above will give a compilation error.
Although not advisable, you can change the value of the argument in a function. However, when the argument is declared as a final, its value cannot be changed.
The above will give a compilation error
Final classes cannot be subclassed. Final methods cannot be overridden. Final variables and final arguments cannot be assigned a value more than once.
Typically, java coding standards say that all variables and all arguments should be declared as final.