21) Final Keyword
Final:
Is a keyword.
The final keyword can be used in many contexts.
final can be:
Variable
Method
Class
If you want to declare constant variables where in the value cannot change, then those variables should be declared with the keyword “final”.
Final variable value cannot be changed or overridden.
Both local and global variable can be final.
Global final variable should be initialized at the time of initialization itself.
Local final variable can be declared once and initialized later.
In terms of inheritance, final keyword us used to avoid overriding.
Final class cannot be inherited.
Final class methods cannot be overridden because for method overriding inheritance is mandatory.
Example:
Output:
Note:
If you make a variable as final then we can never re-initialize that variable.
Static and non-static variable if made Final then its initialization is mandatory or else we will get blank field error.
Example:
Output:
Exception in thread "main" java.lang.Error: Unresolved compilationproblem: The local variable j may not have been initialized
Note:
In case of local variable make it final there is no error, but using it without initialization will throw error.
Example:
Output:
The final local variable i cannot be assigned. It must be blank and not using a compound assignment
Note: If you make an array as final then its size cannot be altered.
Example:
Output:
20
Example:
Output:
Note:
When array is final, its size cannot be changed.
When array is not final, then size can be altered.
When (String[] args) is final, then its size cannot be altered. args[] is a take string no number allowed
Example:
Output:
10
Note:
Inheritance of final class is not possible.
Final Variable value cannot be altered.
Final Array size cannot be altered, but value can be altered.
Final Class, inheritance is not possible and value cannot be inherited.
Example:
Output:
Unresolved compilation problem the type I cannot sub class to final
Note: A final class can inherit the members of non-final class.
Example:
Output:
20
Note:
If you make method as final, meaning that sub classes cannot override this method. The compiler checks and gives an error if you try to override the method.
When we want to restrict overriding then make a method as a final.
Example:
Output:
The above program would throw a compilation error as we cannot override a final method.
Last updated