Final keyword in Java with example
Here you will know use of Final keyword in Java with example code in java programming.
What is Final Keyword in Java?
The final keyword in Java signifies immutability. When applied to a variable, method, or class, it indicates that the entity cannot be altered or overridden after initialization or declaration.
Use of Final Keyword in Java
In Java, the final keyword serves multiple purposes, each providing a different level of immutability and restriction:
final variables
When a variable is declared using the final keyword, it becomes a constant and cannot be modified. The variable declared with the final keyword enables just one assignment; once assigned a value, it cannot be changed again.
final variable example
1 2 3 4 5 6 7 8 9 10 11 | public class ExampleFinalVariable { public static void main(String[] args) { final int MAX_VALUE = 100; // Trying to change the value of MAX_VALUE will result as compilation error // MAX_VALUE = 200; // This line will cause a compilation error System.out.println("The maximum value is: " + MAX_VALUE); } } |
final methods
When a method is defined using the final keyword, it cannot be overridden. The final method extends to the child class, but the child class cannot override or redefine it. It must be used as implemented in the parent class.
final methods 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 Parent { // Declaring a final method final void display() { System.out.println("This is the display method of the Parent class."); } } class Child extends Parent { // Trying to override the final method will result as compilation error /* void display() { System.out.println("This is the display method of the Child class."); } */ } public class ExampleFinalMethod { public static void main(String[] args) { Parent parent = new Parent(); parent.display(); // Output: This is the display method of the Parent class. Child child = new Child(); child.display(); // Output: This is the display method of the Parent class. } } |
final class
When a class is defined using the final keyword, no other class can extend it.
final class example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | final class FinalClass { void display() { System.out.println("This is a final class."); } } // Attempting to inherit from a final class will result as compilation error /* class Subclass extends FinalClass { void display() { System.out.println("This is a subclass of FinalClass."); } } */ public class ExampleFinalClass { public static void main(String[] args) { FinalClass obj = new FinalClass(); obj.display(); // Output: This is a final class. } } |
Check out our other Java Programming Examples