final Keyword
final is used to mark something as unchangeable. A final variable's value can't be reassigned, a final method can't be overridden by subclasses, and a final class can't be extended (inherited from) at all.
1. What is the final Keyword?
final is used to mark something as unchangeable. A final variable's value can't be reassigned, a final method can't be overridden by subclasses, and a final class can't be extended (inherited from) at all.
2. Why is it used?
It's used to protect important values, methods, or entire class designs from being accidentally or intentionally altered elsewhere in the code, keeping certain behaviour guaranteed and consistent.
3. Real-Life Example
Think of a sealed exam paper — once sealed and signed off, its content is locked and cannot be changed. final locks a variable, method, or class in a similar way, depending on where it's applied.
4. Syntax
javafinal dataType variableName = value; final class ClassName { } final returnType methodName() { }
5. Example Program
javaclass Vehicle { final int wheels = 4; final void showWheels() { System.out.println("Wheels: " + wheels); } } public class FinalDemo { public static void main(String[] args) { Vehicle v = new Vehicle(); v.showWheels(); } }
Output:
Wheels: 46. Key Points to Remember
finalvariable: value cannot be changed once assigned.finalmethod: cannot be overridden by a subclass.finalclass: cannot be extended by any other class.