1

I have read some source codes. In the package of util, I saw much usage of 'final' keyword. For instance, there is a method in PrefUtil.java:

public static void setAttendeeAtVenue(final Context context, final boolean isAtVenue) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    sp.edit().putBoolean(PREF_ATTENDEE_AT_VENUE, isAtVenue).commit();
}

In this method, all parameters are modified by 'final'. And I encountered a few cases like this somewhere else. But I didn't understand the effect of 'final'. So, I ask for help here to erase questions in my mind.

3 Answers3

0

Using final ensures that the references being passed are not reassigned. You can modify the object to which the reference points. Thus, your object is not immutable, it is still mutable but the reference cannot be reassigned.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

final means you can't change the value of that variable once it was assigned

The use of final for the arguments in those methods means it won't allow the programmer to change their value during the execution of the method.

MihaiC
  • 1,618
  • 1
  • 10
  • 14
0

final on parameter will prevent code inside method to rewrite it.

Rewriting parameter values is bad practice since it's very difficult to maintain such code.

pbespechnyi
  • 2,251
  • 1
  • 19
  • 29
  • Yeah, I thought I got it. And there is the similar question with me, whose url is here : http://stackoverflow.com/questions/2236599/final-keyword-in-method-parameters –  Dec 21 '14 at 09:28
  • Yeah, but parameters are not rewritted. So 'final' is unnecessary, right? –  Dec 21 '14 at 09:34
  • @LittlePanpc, well, methods can grow quickly, so `final` here is to protect params from future changes. But, on my projects `final` on params is used very rarely. – pbespechnyi Dec 21 '14 at 20:08