Search code examples
javaparametersoverridingfinalsuperclass

Should I make all parameters in Java/Android final?


In this answer it is states that you should never change parameters you assign and it would be best if Java would enforce parameters to always be final. I personally agree and never do this. If I want to change something to the parameter and then return it again, I create a local copy in the method, change things about that copy and then return that copy.

This made me wonder, should I make all parameters in my Android/Java project final, or is there a case where I wouldn't want to do this?

Some questions that popped up in my head:

  • Does making a @Override method's parameters final make a different?
  • And as a follow-up to the previous question: Does it matter if I call super(my_final_parameter);?
  • Again a follow-up: With the super(my_final_parameter); of default Java/Android extends, is there any case behind the scenes where these Java/Android classes use the parameter so I can't have them final?

If it doesn't matter for the cases above (or other cases you might think of) if the parameters are final or not, is it a good idea to make every parameter of methods / constructors / overridden methods final?


Solution

  • Since Java is pass-by-value and not pass-by-reference, modifying your parameters would have no effect on the original variable.

    Adding final to your parameters avoids to whoever has to modify your code (also you) to run in this "bug". So it's up to you, if you want to be sure to not trying to modify your parameter thinking it will modify your variable, use final.

    I personally don't use this practice since I'm aware of this behavior (and my first language is java).

    As for your popped out questions they asnwer quite by themselves having understood the above. An overriding method simply is a different implementation of a super method, the super parameters have nothing to do with its runtime behavior, since the overriding method is chosen. Also calling super(final_var), as java is pass-by-value, simply passes the value to the super class, leaving final_var untouched and thus not violating the final modifier.