What is the final Keyword in Java?
The final keyword is used to create constants (variables), prevent method overriding, and prevent inheritance (classes).
1. final Variables (Constants)
Once initialized, value cannot be changed.
class Constants {
final double PI = 3.14159;
final int MAX_VALUE;
// Blank final variable - must initialize in constructor
Constants(int max) {
MAX_VALUE = max;
}
void demonstrate() {
// PI = 3.14; // ERROR: Cannot reassign final variable
System.out.println("PI: " + PI);
System.out.println("MAX: " + MAX_VALUE);
}
}
2. final Methods (Prevent Overriding)
Cannot be overridden by subclasses.
class Parent {
final void display() {
System.out.println("Parent display - cannot override");
}
void normalMethod() {
System.out.println("Normal method");
}
}
class Child extends Parent {
// void display() { } // ERROR: Cannot override final method
@Override
void normalMethod() { // OK - can override non-final
System.out.println("Child normal method");
}
}
3. final Classes (Prevent Inheritance)
Cannot be extended/subclassed.
final class MathConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
public static double circleArea(double radius) {
return PI * radius * radius;
}
}
// class ExtendedMath extends MathConstants { } // ERROR: Cannot extend final class
final Parameters
class Calculator {
int add(final int a, final int b) {
// a = 10; // ERROR: Cannot modify final parameter
return a + b;
}
}
final vs Immutability
Important: final means reference cannot change, but the object itself can be mutable.
final StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // OK - modifying object content
// sb = new StringBuilder("New"); // ERROR: Cannot reassign final reference
Quick Reference
| Applied to | What it prevents |
|---|---|
| Variable | Reassignment (value change) |
| Method | Overriding by subclass |
| Class | Inheritance/subclassing |
Master Java keywords with Online Learner!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
