Java Final Keyword
In Java, the final
keyword is used to indicate that a variable, method, or class cannot be modified or extended. Once a variable is declared as final, its value cannot be changed. Similarly, once a method is declared as final, it cannot be overridden by a subclass. Finally, if a class is declared as final, it cannot be subclassed.
Syntax
For Variables
final data_type variable_name = value;
For Methods
access_modifier final return_type method_name() {
}
For Classes
final class class_name {
}
Example
Final Variable
final int MAX_VALUE = 10;
// MAX_VALUE cannot be changed now
Final Method
class Animal {
public final void sound() {
System.out.println("Animal is making a sound!");
}
}
class Cat extends Animal {
// This will give a compile-time error since sound() is final in Animal class
public void sound() {
System.out.println("Meow!");
}
}
Animal a = new Animal();
a.sound(); // Output: Animal is making a sound!
Final Class
final class Animal {
}
// This will give a compile-time error since we cannot extend a final class
class Cat extends Animal {
}
Output
Animal is making a sound!
Explanation
The use of the final
keyword provides the assurance that the value of a variable will not be changed, a method cannot be overridden, or a class cannot be subclassed. Once the value of a final variable is assigned, it cannot be changed further.
The use of the final
keyword in a method indicates that the method cannot be overridden by a subclass. If a subclass attempts to override the final method, a compile-time error is generated.
Finally, if a class is declared final, it cannot be subclassed. This can be useful when the class is designed to be used as is and any modification to the behavior would be detrimental to the program.
Use
- To create constant variables that cannot be modified.
- To prevent a class from being subclassed.
- To prevent a method from being overridden.
Important Points
- A
final
variable cannot be reassigned after being initialized. - A
final
method cannot be overridden by a subclass. - A
final
class cannot be subclassed. - The
final
keyword can be applied to variables, methods, and classes.
Summary
In Java, the final
keyword is used to indicate that a variable, method, or class cannot be modified or extended. The use of the final
keyword provides assurance that a variable will not be accidentally modified, a method will not be overridden, or a class will not be subclassed. The final
keyword can be applied to variables, methods, and classes.