Final Method in Java
beginner· OOP · Modifiers
Problem
A method declared final can still be inherited and called normally by subclasses, but none of them can override it — the class itself remains free to be extended, only that one method's behavior is locked.
Define an Employee class with a final getEmployeeId() method, and a Manager subclass that inherits and uses it as-is.
Input
new Manager().manageTeam()
Output
Managing team, ID: EMP-1001
Java Program
Java
class Employee {
final String getEmployeeId() {
return "EMP-1001";
}
void work() {
System.out.println("Working...");
}
}
class Manager extends Employee {
// Cannot override getEmployeeId() here — inherits it as-is
void manageTeam() {
System.out.println("Managing team, ID: " + getEmployeeId());
}
}
public class FinalMethodDemo {
public static void main(String[] args) {
Manager m = new Manager();
m.manageTeam();
}
}Output
Managing team, ID: EMP-1001
Core Logic
Marking only getEmployeeId() as final, while leaving the Employee class itself open to extension, locks down one specific piece of behavior without restricting the whole class.
How It Works
- 1
final String getEmployeeId()can be inherited and called by any subclass, but attempting to override it inManagerwould fail to compile. - 2
class Manager extends Employeeis still allowed — only the onefinalmethod is protected, not the whole class. - 3
manageTeam()callsgetEmployeeId()without redefining it, using the exact implementation inherited fromEmployee. - 4Every subclass of
Employee, present or future, is guaranteed to return the same ID format fromgetEmployeeId().
new Manager().manageTeam() calls the inherited getEmployeeId(), which always returns "EMP-1001", printing "Managing team, ID: EMP-1001".💡
Key Point: This is a finer-grained lock than a final class — Employee can still grow new subclasses freely, but getEmployeeId()'s behavior is guaranteed identical across every one of them.
Key Concepts
final methodprevent overridinginherited behavior