Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why we make method parameters final.

 
Arav Kumar
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi to all Ranchers,

Please explain what is the reason and use to make method parameters final. In what circumstances we make method parameters final.


Regards
Arav Kumar.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wouldn't normally make method arguments final; arguments are passed by value, if you change the variable, it will not change the original variable in the calling method - so it doesn't really make sense to make arguments final.

There is one case in which you might want to do it: if you need to use the argument in an anonymous inner class. For a local variable (or argument) to be used in an anonymous inner class, it must be final. For example:

 
Rok Štelcer
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

You should declare a parameter as final, when/if it’s going to be used in a local inner class.
For example:

Hope this helps.


Regards,
Rok
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is often unnecessary, but it can't do any harm to declare arguments final. That simply means you are promising the compiler you won't re-assign them in the method. Usually unnecessary (except when required for an anonymous inner class).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic