Java final keyword
Final Keyword is used to stop user accessing the java variable or class or method. We can use final keyword in following three manner -
- Making Final Variable
- Making Final Method
- Making Final Class
Contents
Way 1 : Final Variable
If we make the variable final then the value of that variable cannot be changed once assigned. Consider the following example -
package com.c4learn.inheritance; public class ShapeClass { final int SHAPE_SIDES = 3; void setShape() { SHAPE_SIDES = 4; } public static void main(String[] args) { ShapeClass c1 = new ShapeClass(); c1.setShape(); } }
Output :
Compile Time Error
We cannot modify the value of the final variable, we will get following error message -
Way 2 : Final Method
We cannot Override the final method as we cannot change the method once they are declared final. Consider the following example -
package com.c4learn.inheritance; public class ShapeClass { int SHAPE_SIDES = 3; final void setShape() { SHAPE_SIDES = 4; } public static void main(String[] args) { ShapeClass c1 = new ShapeClass(); c1.setShape(); } } class Circle extends ShapeClass { void setShape() { // Error Here SHAPE_SIDES = 4; } }
Output :
Compile Time Error
In this example we have declared method as final so we cannot override the final method, otherwise we will get compile time error -
Way 3 : Final Class
We cannot inherit the final class.
package com.c4learn.inheritance; public final class ShapeClass { int SHAPE_SIDES = 3; final void setShape() { SHAPE_SIDES = 4; } public static void main(String[] args) { ShapeClass c1 = new ShapeClass(); c1.setShape(); } } class Circle extends ShapeClass { // Error Here }
Output :
Compile Time Error
In this example we have declared class as final so we cannot inherit the final class
Some Important Points : Final Keyword
- Final Keyword can be applied only on Method,Class and Variable
Final Entity | Description |
---|---|
Final Value | Final Value cannot be modified |
Final Method | Final Method cannot be overriden |
Final Class | Final Class cannot be inherited |
- Final Variable must be initialized at the time of declaration or inside constructor
- Re-Assigning Value is not allowed for final member variable
- Local Final Variable should be initialized during the time of declaration
- Final and Finally both are different. Finally keyword is used on Exception handling in Java