OOP · Core Java OOP Features
final Keyword
Employee ID. Once assigned, the ID should never change.
Real-World Problem
Imagine an Employee Management System where every employee has a unique Employee ID. Once assigned, the ID should never change. Why Do We Need final? The final keyword prevents modification, inheritance, or method overriding, helping create secure and immutable code. What is final?
The final keyword is used to restrict changes to variables, methods, and classes.
Uses of final
Final Variable Its value can be assigned only once.
Final Method Cannot be overridden by child classes.
Final Class Cannot be inherited by another class.
final freezes things: constants, un-reassignable references, and un-extendable classes/methods.
final class MathUtil { // cannot be subclassed
static final double PI = 3.14159; // compile-time constant
final int factor; // must be set once, then fixed
MathUtil(int factor) { this.factor = factor; }
final int scale(int n) { // cannot be overridden
return n * factor;
}
}