Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CheckStyle suggest that I use a final method?

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?

like image 339
Mansuro Avatar asked Mar 21 '12 09:03

Mansuro


2 Answers

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.

like image 186
aioobe Avatar answered Sep 27 '22 22:09

aioobe


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!)

like image 45
Jeff Foster Avatar answered Sep 27 '22 23:09

Jeff Foster