Hello Everyone. This is Gautam, and today's topic is Final Keyword in Java in easiest way, After reading this post you will have no doubt,
Final Keyword in Java
Definition : In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once. Once a final variable has been assigned, it always contains the same value. Final Can Be
- Final variable
- Final method
- Final class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
Test it Now
Output: Compile Time Error
2. Java final method
If you make any method as final, you cannot override it.
Example of final method
Test it Now
Output: Compile Time Error
3. Java final class
If you make any class as final, you cannot extend it.
Example of final class
Output: Compile Time Error
_-_-_-_-_-_-_-Doubt Questions_-_-_-_-_-
Q1) Is final method inherited?
Ans--> Yes, final method is inherited but you cannot override it.
For Example:
Output: running...
Q2) What is blank or uninitialized final variable?
Ans--> A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Example of blank final variable
Q3) Can we initialize blank final variable?
Ans--> Yes, but only in constructor. For example:
Output: 100
Q4) what is static blank final variable ?
Ans--> A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
Example of static blank final variable
Q5) What is final parameter ?
Ans--> If you declare any parameter as final, you cannot change the value of it.
THANKS FOR VISITING THIS BLOG PAGE 💖.
0 Comments