Final Keyword in Java
Introduction to Final Keyword in Java
The final keyword in Java is used to restrict modification. It is an important concept for writing secure and predictable code. It allows developers to define constants, prevent method overriding, and restrict inheritance.
After learning the static keyword, understanding final helps in controlling behavior and improving code stability.
What is Final Keyword in Java
The final keyword is a non access modifier used with variables, methods, and classes. It prevents changes once a value or definition is assigned.
The behavior of final depends on where it is used.
Final Variable in Java
A final variable is a constant whose value cannot be changed once assigned. It must be initialized either at the time of declaration or inside a constructor.
Example of Final Variable
final int value = 10;
void display() {
// value = 20; not allowed
System.out.println(value);
}
}
Final Method in Java
A final method cannot be overridden by subclasses. It ensures that the original implementation remains unchanged.
Example of Final Method
final void show() {
System.out.println(“Final method”);
}
}
class Child extends Parent {
// void show() { } not allowed
}
Final Class in Java
A final class cannot be extended or inherited. It is used to prevent class modification.
Example of Final Class
void display() {
System.out.println(“Final class”);
}
}
// class Test extends Demo { } not allowed
Key Features of Final Keyword
Final variables cannot be reassigned. Final methods cannot be overridden. Final classes cannot be inherited. It helps in creating immutable and secure code.
Advantages of Final Keyword in Java
Final improves security by preventing unwanted changes. It helps in creating constants and ensures stable behavior of methods and classes. It is useful in designing reliable applications.
Disadvantages of Final Keyword
Overuse of final can reduce flexibility in code. It restricts inheritance and method overriding, which may not always be desirable.
Real World Example of Final Keyword
In an application, values like pi or configuration constants can be declared as final so they cannot be changed. Similarly, critical methods can be marked final to prevent modification in subclasses.
Common Mistakes in Final Keyword
Trying to modify a final variable causes errors. Attempting to override a final method is not allowed. Declaring classes as final without understanding inheritance requirements can limit flexibility.
Interview Questions on Final Keyword in Java
What is final keyword in Java
What is a final variable
What is a final method
What is a final class
Can we override a final method
FAQs
What is final keyword in Java in simple terms
Final keyword is used to restrict changes in variables, methods, and classes.
Why do we use final in Java
It is used to create constants and prevent modification.
Can a final class be inherited
No a final class cannot be extended.
