Java final Keyword:
- The final keyword in Java is used to restrict the user.
- It is used to create a variable in the form of continuous, prohibiting the inheritance, restricting the inheritance override. It is used at variable level, method level and class level.
Java final keyword can be used with:
final variable:
- When a variable is declared with the final keyword, its value can not be modified, essentially, continuously.
- It also means that you should start the final variable.
- If the last variable is a reference, then it means that the variable can not be re-bound to refer to any other object.
- Internal position of the object pointed in the reference context can change, i.e. you can use the last array or the last Can add or remove elements from the collection.
- All uppercase is a good practice to represent the last variable, underlining different words.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class FinalVariable_Java { final int VALUE = 99; void myMethod() { VALUE = 101; } public static void main(String args[]) { FinalVariable_Java obj = new FinalVariable_Java(); obj.myMethod(); } } |
Output:
1 2 3 | Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field FinalVariable_Java.VALUE cannot be assigned |
Note: We got a compilation error in the above program because we tried to change the value of a final variable.
final method:
- A method declared in the final form can not be overridden.
- This means that when a child class can call the final method of parent class without any problems, it will not be possible to override it using java final keyword.
Example:
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 | class FinalMethod_Java{ final void demo(){ System.out.println("FinalMethod_Java Class Method"); } } class ABC extends FinalMethod_Java{ void demo(){ System.out.println("ABC Class Method"); } public static void main(String args[]){ ABC obj= new ABC(); obj.demo(); } } |
Output:
1 | The above program would throw a compilation error. |
final class:
- The class with the final keyword is known as the final class in Java.
- The final class is completely in nature and can not be inherited.
- Many classes in Java are final, integer and other wrapper squares.
- The main purpose or purpose of using the ultimate objective is to prevent the class from being a sub-class.
- If a class is marked as final, then no class can get any facility from the final class.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | final class FinalClass_Java { } class ABC extends FinalClass_Java { void demo() { System.out.println("My Method"); } public static void main(String args[]) { ABC obj = new ABC(); obj.demo(); } } |
Output:
1 | Compile Time Error. |