In Java, the final
keyword is a non-access modifier applicable for classes, methods, and variables. When the final
keyword is applied to a method, it means the method cannot be overridden in a subclass.
To understand this concept better, let's delve into an example.
class Parent {
final void demoMethod() {
System.out.println("This is the method from superclass");
}
}
class Child extends Parent {
void demoMethod() {
System.out.println("This is the method from subclass");
}
}
public class Test {
public static void main(String args[]) {
Child obj = new Child();
obj.demoMethod();
}
}
In the above example, you will get a compilation error because the demoMethod()
in the Child
class is trying to override demoMethod()
in the Parent
class, which has been marked as final
.
Now, you must be wondering, why would you want to use final
for a method? There can be several reasons for this:
final
. It supports the notion of 'unchanging' or 'constant'.final
. This is often done for security reasons or to ensure the logic of the method isn't changed.Remember, though, that using final
should be well-considered. If used carelessly, it can lead to rigidity in the code, making it difficult to extend functionality or apply changes.
It is a common expectation that subclasses should behave as "true" subtypes of their superclass. They should share behavior and semantic properties. If you're creating a method that doesn't adhere to these expectations if subclassed, rather than allowing subclasses to override the method and possibly break these expectations, it's useful to make this method final
.
Remember, when you seal a method by making it final
, make sure to clearly document your reasons, so others are aware of the intent behind it.
In conclusion, the final
keyword when applied to a method in Java means that the method cannot be overridden in a subclass. It's a powerful tool to safeguard, optimize, and maintain the integrity of our code.