The final keyword in Java is used to restrict modification. Depending on where it is applied, it can prevent a variable's value from being changed, stop a method from being overridden, or prevent a class from being inherited. It helps create more secure, stable, and predictable code.
Key Points: • A final variable can be assigned a value only once. • A final method cannot be overridden by a subclass. • A final class cannot be extended by another class. • final is commonly used to create constants. • It improves code safety by preventing unintended modifications.
Example: A banking application may use a final variable for a fixed interest rate that should not change during program execution.
Code Example:
class Bank {
final double INTEREST_RATE = 7.5;
void display() {
System.out.println("Interest Rate: " + INTEREST_RATE);
}
}
public class Demo {
public static void main(String[] args) {
Bank bank = new Bank();
bank.display();
}
}Output:
Interest Rate: 7.5
Types of final:
1. Final Variable
class Employee {
final int employeeId = 101;
void update() {
// employeeId = 102; // Compilation Error
}
}A final variable cannot be reassigned after initialization.
2. Final Method
class Parent {
final void display() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
// void display() { } // Compilation Error
}A final method cannot be overridden.
3. Final Class
final class Utility {
}
class Test extends Utility { } // Compilation ErrorA final class cannot be inherited.
Real-World Examples:
• String class is final to prevent modification through inheritance. • Constants are often declared using static final. • Security-sensitive methods can be declared final to prevent overriding.
Common Usage:
public static final double PI = 3.14159;
Here:
• public → Accessible everywhere • static → Belongs to the class • final → Cannot be modified
Benefits:
• Prevents accidental changes • Improves code reliability • Enhances security • Supports immutable object design
Interview Tip: A concise interview answer is:
"The final keyword is used to restrict modification in Java. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. It is commonly used for constants, immutable objects, and securing class behavior."