What is the final method in Java?
In Java, the final
keyword can be applied to classes, methods, and variables, and it serves different purposes in each context. When it comes to methods, declaring a method as final
means that the method cannot be overridden by subclasses. This is useful when you want to ensure that the specific implementation of a method remains unchanged in any derived class.
Here’s a simple example to illustrate the use of a final method:
class Parent {
// This method cannot be overridden in any subclass
public final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// This will cause a compile-time error
// public void display() {
// System.out.println("Trying to override a final method.");
// }
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display(); // This will call the final method from Parent
}
}
Using final methods is a design choice that can help enforce certain behaviors in your class hierarchy.