Preventing Method Overriding with final
What you'll learn: How to use final on methods to lock down their behavior and prevent subclasses from changing them.
The Core Idea
In the previous lesson, you learned that the final keyword can be applied to methods. When you mark a method as final, you're telling Java: "This method's behavior is complete and must not be changed by any subclass." If a subclass attempts to override a final method, the compiler will reject your code with an error.
Why Lock Down a Method?
Sometimes you create a method whose behavior is critical to your class's correctness or security. You want to guarantee that no subclass can alter this behavior, even accidentally. Marking it final provides that guarantee.
Analogy: Think of a final method like a sealed instruction manual. The manufacturer says, "Follow these steps exactly—don't modify them." Subclasses can read and use the method, but they can't rewrite it.
What Happens When You Try to Override
If you attempt to override a final method in a subclass, Java produces a compile-time error. This is intentional—it catches mistakes early, before your program runs.
class Parent {
public final void criticalOperation() {
System.out.println("Critical logic");
}
}
class Child extends Parent {
@Override
public void criticalOperation() { // COMPILE ERROR!
System.out.println("Trying to change it");
}
}
The compiler error message will say something like: "Cannot override the final method from Parent."
When to Use final Methods
Use final when a method's implementation must remain unchanged for correctness, security, or design reasons. Common examples include methods that perform security checks or maintain critical invariants.
Key Takeaway: Marking a method final prevents any subclass from overriding it, enforcing consistent behavior and catching override attempts at compile time.