Final Classes, Methods, Variables, and Arguments in Java.
After working with several Java developers of varying skill levels, I have found that the “final” keyword is the most underused concept practiced by them. I have found great reasons to use “final” in my coding and I wanted to share some of them.
Final Class
- A class is called final class when it is declared with the final keyword.
- Final class cannot be inherited.
- Why do we want to make a class as final?
- When you want to do an immutable programming
- If you do not want somebody to extend the class, then use the final class.
- Whenever somebody extends a class they have the privilege of modifying some of the code inside those class methods, if we do not want to allow it, in certain situations.
Example
All Wrapper Classes like Integer, Float, etc. are final classes. We cannot inherit them.
Nobody will be able to extend the above class.
Final Methods
- We can declare some or all methods final.
- Use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses.
- The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Final Variable
The only difference between a normal variable and a final variable is that we can re-assign value to a normal variable but we cannot change the value of a final variable once assigned. Hence, final variables must be used only for the values that we want to remain constant throughout the execution of the program.
Example of final variable
- In the above example, we can change the variable i from 5 to 7.
- If we do not want to change the value, we will make variable i as final.
- Here we have declared variable i as final so changing i value is not allowed.
Final argument
Here below, we have not declared argument as final.
- In the bellow example doSomethingElse() method declared as final int argument.
- So it restrict to change the value of doSomethingElse() method argument.
0 Comment