Final Keyword In JAVA | Core Java Tutorial | Minigranth
Final Keyword In Java : Introduction
Java final keyword is used as prevention, i.e. it restricts user.
Java final keyword has three uses :
It can be used with variables to prevent their values from being changed.
It can be used to prevent overriding.
It can be used to prevent inheritance.
Final Keyword In Java : The Discussion
final with Variables
If any variable is made final , it restricts the user to changes its value i.e. the content of variable cannot be changed.
Note : A blank variable can also be declared as final and it will be initialized in constructor only, because constructor are invoked as soon as object of that class is created.
Example
Final With Variable : Example
Final With Variable : Output
We tried to change the final variable and compiler throws an error which is stated in output.
final with Method
The only purpose of using final with method is to prevent method overriding.
When a method is declared as final then it cannot be overridden. If we try to do so , we get a compile time error. Let us understand with an example.
Example
Final With Method : Example
Final With Method : Output
In the above images, We tried to override a final method and got an error.
final with Class
A class preceded with final keyword cannot be inherited.
Final keyword prevents a class from getting inherited and also implicitly declares all of its methods as final.