Understanding the final
Keyword in Java
In Java, the final
keyword is powerful tool used to restrict modification. Whether applied to variables, methods, or classes, final
enforces immutability and prevents unexpected behavior, making your code more robust and secure.
In this blog, will break down how final
keyword works in Java covering final variables, final methods, and final classes along with examples.
What Does final
Do?
final
keyword can be used in three main contexts:
- Final variables
- Final methods
- Final classes
1. Final Variables
When variable is declared as final
, its value cannot be changed once initialized. Trying to reassign final
variable will result in compile-time error.
Example:
final int x = 10; x = 20; // Compile Time Error: cannot assign value to final variable
Blank Final Variable
You can declare a final
variable without assigning value this is called a blank final variable. It must be initialized either in the constructor or during object creation.
class A { final int speed; A() { speed = 100; // Initialized in constructor } }
Static Blank Final Variable
static final
variable that isnβt initialized during declaration is known as static blank final variable. It must be initialized in static block.
class A { static final int data; // static blank final variable static { data = 50; } public static void main(String[] args) { System.out.println(A.data); } }
2. Final Methods
When a method is declared as final
, it cannot be overridden by any subclass. This is especially useful when you want to prevent modification of critical functionality.
class Bike { final void run() { System.out.println("Running..."); } } class Honda extends Bike { // void run() { System.out.println("Running safely"); } // Compile Time Error }
3. Final Classes
If class is declared as final
, it cannot be extended. This is often done for security or to prevent alteration of core behavior.
final class Vehicle { void start() { System.out.println("Vehicle started"); } } // class Car extends Vehicle {} // Compile Time Error
Conclusion
final
keyword helps enforce immutability, security, and clarity in Java code. Whether you are preventing variables from being modified, methods from being overridden, or classes from being extended, final
plays a crucial role in writing clean, error-free code.
Top comments (0)