final-keyword
The final keyword in Java is a fundamental modifier used to impose restrictions on variables, methods, and classes. Its primary purpose is to prevent changes, ensuring code safety and clarity. Let’s explore how final works in different contexts.
1. Final Variables
A variable declared with the final keyword becomes a constant. Once assigned, its value cannot be changed.
Syntax:
A variable declared with the final keyword becomes a constant. Once assigned, its value cannot be changed.
Syntax:
final data_type variableName = value;
Example:
final double PI = 3.14159;// PI = 3.14; // This will cause a compilation errorSystem.out.println(PI);
Note: Attempting to reassign a final variable results in a compile-time error.
2. Final Methods
A method marked as final cannot be overridden by subclasses. This is useful when you want to ensure that the core logic of a method remains unchanged in any derived class.
Syntax:
A method marked as final cannot be overridden by subclasses. This is useful when you want to ensure that the core logic of a method remains unchanged in any derived class.
Syntax:
class Parent { final void display() { // method body }}
Example:
class Parent { final void show() { System.out.println("This is a final method."); }}
class Child extends Parent { // Attempting to override show() will cause a compilation error // void show() { ... }}
Note: Overriding a final method leads to a compilation error.
3. Final Classes
A class declared as final cannot be subclassed. This is typically used to prevent inheritance for security or design reasons.
Syntax:
A class declared as final cannot be subclassed. This is typically used to prevent inheritance for security or design reasons.
Syntax:
final class MyClass { // class body}
Example:
final class Vehicle { // class code}
// The following will cause a compilation error// class Car extends Vehicle { }
Note: Extending a final class is not allowed in Java.
When to Use the final Keyword
- Constants: Use final variables for values that should remain constant throughout the program.
- Security: Use final methods and classes to prevent unwanted modification or extension.
- Immutability: Helps in creating immutable classes, especially in multi-threaded applications.
The final keyword is a simple yet powerful tool for writing robust, secure, and maintainable Java code. Understanding when and how to use it is essential for any Java developer.