⬅ Previous Topic
Java final VariablesNext Topic ⮕
Java final class⬅ Previous Topic
Java final VariablesNext Topic ⮕
Java final classIn 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
?
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.
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.
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.
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.
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
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.
final
methods cannot be overridden.class Parent {
final void display() {
System.out.println("Parent method");
}
}
class Child extends Parent {
void display() {
System.out.println("Child method");
}
}
class Example {
final void test() {
System.out.println("No parameters");
}
void test(int x) {
System.out.println("One parameter: " + x);
}
public static void main(String[] args) {
Example ex = new Example();
ex.test();
ex.test(42);
}
}
⬅ Previous Topic
Java final VariablesNext Topic ⮕
Java final classYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.