In Java, the keyword final with methods is used to preserve design integrity, prevent misuse, and encourage safe code extension. But what exactly does it mean to make a method final?
What is a final method?
A final method is a method that cannot be overridden by subclasses. This ensures that the core behavior defined in the method remains consistent and unchangeable when inherited.
This is particularly useful when designing frameworks or libraries, where certain base functionalities should never be altered by child classes.
Syntax of final methods
class Parent {
final void show() {
System.out.println("This is a final method.");
}
}
Any class that extends Parent will inherit the method show(), but will not be allowed to override it.
Why use final methods?
- To prevent unexpected behavior from subclass overrides
- To ensure critical business logic is not changed
- To improve performance (some JVMs optimize final methods)
Example: Attempting to Override a Final Method
class Parent {
final void display() {
System.out.println("Display from Parent");
}
}
class Child extends Parent {
// Uncommenting below will cause a compile-time error
// void display() {
// System.out.println("Display from Child");
// }
}
Compile-time Error: Cannot override the final method from Parent
Explanation: The compiler blocks the attempt to override the display() method because it’s declared final in the parent class.
Valid Usage: Calling a Final Method in a Subclass
class Parent {
final void greet() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
void welcome() {
greet(); // Valid: calling inherited final method
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.welcome();
}
}
Hello from Parent
Though the method greet() is final and can’t be overridden, it can still be inherited and called like any other method.
Can a final method be overloaded?
Yes! Overloading is based on the method signature (name and parameters), not inheritance. So you can define methods with the same name but different parameter lists—even if one version is final.
class Example {
final void test() {
System.out.println("No parameters");
}
void test(int x) {
System.out.println("One parameter: " + x);
}
}
No parameters
One parameter: 42
Conclusion
The final keyword in methods is a safeguard. It’s used by developers who want to make sure the rules aren’t rewritten downstream. Use it wisely in scenarios where the base method's logic must be preserved across the inheritance chain.
Key Takeaways
finalmethods cannot be overridden.- You can still call and inherit final methods.
- Final methods can be overloaded.
- Use them when you want to lock down method behavior for reliability.
