- Eclipse: Oxygen
- Java: 1.8
Final Keyword
Final keyword can be applied to variables, methods, classes, etc. It is used in various contexts to define an entity that can only be assigned once. Once a final variable has been assigned, the variable cannot be changed. Therefore, the user tries to change the value using the setter or the constructor, and then the errors are entered into the program.
Final variable
If you make a variable as final, you cannot change the value of the final variable. There is a final variable x, we are going to change the value of this variable, but it cannot be changed because we have defined the final variable in constructor B().
If you make a variable as final, you cannot change the value of the final variable. In the following program, there is a final variable x.
A variable that is not initialized at the time of declaration is known as a final blank variable. We must initialize the final variable in the constructor of the class, otherwise, it will throw a compilation error.
Program folder structure
Program code:
A.java
1 2 3 4 5 |
package org.studyeasy; public class A { } |
App.java
1 2 3 4 5 6 7 8 9 10 11 |
package org.studyeasy; public class App { public static void main(String[] args) { B obj1 = new B(12); System.out.println(obj1.getX()); } } |
B.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package org.studyeasy; public class B extends A{ private final int x; public B(int x) { super(); this.x = x; } public int getX() { return x; } } public class A { } public class App { public static void main(String[] args) { B obj1 = new B(12); System.out.println(obj1.getX()); } } |
Output
12
Contributed by Salim Sheikh