I am using eclipse checkstyle plugin. I have few methods in a class A which are overriden in class B. I have the following warning for most of the methods
The function
SearchAndReplace
is not conceived to be inherited
- it must be declared abstract or final or leave it empty.
Is there a any advantages to declaring a method as final?
EDIT
I know what the keyword final is for. I know it prevents overriding of methods, is there other advantages, like performance or anything like that?
When you declare a method to be final, you're saying that the method may not be overridden.
Quote from the Java Language Specification:
A method can be declared final to prevent subclasses from overriding or hiding it.
It is a compile-time error to attempt to override or hide a final method.
The common slogan (due to Joshua Bloch I believe) is
"Design and Document for Inheritance or Else Prohibit it"
So, unless your intention is to let subclasses override the method (and potentially change the behavior of the super-class (all methods are virtual in Java)) then make the method final.
A final
method guarantees that no subclasses will override the method. Chances are that the runtime can take advantage of this for a performance gain (which may be slight).
The main reason for making a method final
is to stop inheritors overriding the method. This might be an important consideration (for example, imagine a method called bool checkSecurity()
- letting others override this would be bad!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With