Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why method parameters needs to be set as final?

I have enabled Checkstyle for my project. It is showing yellow mark on method parameters and requesting to set it as final. Why? What is the purpose? If not specified what will be the problem?

like image 427
Jothi Avatar asked Sep 03 '10 12:09

Jothi


People also ask

Should method variables be final?

Method parameters and local variables should not be declared final unless it improves readability or documents an actual design decision. Fields should be declared final unless there is a compelling reason to make them mutable.

Why is method made final?

The main reasoning behind making a method final is to prevent it from being overridden by subclasses. By making a method final, you not only indicate but also ensures that your tried and tested method is not overridden.

Why variables are final and why methods are not final?

If we initialize a variable with the final keyword, then we cannot modify its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it.

What is the purpose of method parameters?

The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in. Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked.


1 Answers

In case there is a rule in Checkstyle, normally the answer is there as well: http://checkstyle.sourceforge.net/config_misc.html

In this case:

Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. A great way to let the Java compiler prevent this coding style is to declare parameters final.

like image 118
Balazs Zsoldos Avatar answered Oct 21 '22 05:10

Balazs Zsoldos