The final Keyword on Methods
What you'll learn: How marking a method final prevents subclasses from overriding it, and when you'd want that protection.
Locking Down a Method's Behavior
When you declare a method as final, you're telling Java: "This method's implementation must never change in any subclass." It's like sealing a blueprint so nobody downstream can modify that particular part of the design.
Why Prevent Overriding?
You've already seen how subclasses can override methods to change behavior. But sometimes you need a method to work exactly as written:
- Critical logic: Methods involved in security, mathematical calculations, or core algorithms that must remain consistent
- Template methods: When your method calls other overridable methods in a specific sequence that shouldn't be altered
- Performance: The JVM can optimize
finalmethods more aggressively since it knows the implementation won't change
The Syntax
Simply add final before or after the access modifier:
public final void calculateTax() {
// This exact logic will be used by all subclasses
double tax = price * TAX_RATE;
totalPrice = price + tax;
}
If a subclass tries to override a final method, the compiler immediately produces an error—no runtime surprises.
Think of It as a Contract
It's like a recipe passed down through generations: you can add new recipes (new methods), but Grandma's secret sauce recipe (the final method) must stay exactly as written. No substitutions allowed.
Key Takeaway: The final keyword on methods prevents any subclass from overriding that method, ensuring the behavior remains unchanged throughout the inheritance hierarchy.