简体   繁体   中英

Java and the use of the Final keyword

I'm new to Java having programmed in Delphi and C# for some time,. My question relates to the usage of the "final" keyword on a variable that holds an instantiated class when the variable declaration and instantiation both happen within the scope of the same method. eg

private String getDeviceID() {
   //get the android device id
   final TelephonyManager tm =                
     (TelephonyManager)GetBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
   final String deviceID = tm.getDeviceId();

   // log debug message containing device ID
   Log.d(LOG_CAT, "getDeviceID: " + deviceID);        

   return deviceID;
}

okay so I think I get the fact that "final" variables can only ever be assigned to once and cannot be changed due to the "final" keyword on each declaration, but don't both variables go out of scope when the method exits? and calling the method again will simply reallocate 2 new final variables that once again will go out of scope on method exit?

To me it seems kinda odd to be using the "final" keyword on these variables? unless I don't understand how they impact on local variables within a method's scope?

Can someone enlighten me as to what the impact of "final" is with regard to method scope, or is declaring these particular variables as final just a dumb ass thing that someone did?

final has no effect on scope.
It just prevents the variable from being re-assigned.

It serves as a signal to other developers that these variables will never change, and it prevents you from changing them by accident.
This is particularly useful in longer methods.

final is also required in order to use a variable in an anonymous inner class, since Java does not support true closures.

These variables will indeed be garbage collected as soon as the GC will run when the method exits.

The final keyword is really there as a hint: this variable is instantiated once, you should not touch it in the body of the method itself. Similarly, declaring method parameters final forbids their reuse (which, imho, is a good thing).

Note however that the keyword only affects the object reference: it does not mean that methods on this object reference which modify its internal state will cease to work (typical example: setters).

Another note: when you omit the final keyword, and you don't modify the variable in the body of your method, the JVM is smart enough to optimize this case. So, you may omit it. Whether or not you use it, and where you use it, is a matter of taste/coding style.

And finally, it is good practice to declare public static variables as final: otherwise, anything can modify it! Think string constants etc.

There's nothing special about the scope of a final local variable or parameter.

Declaring a local variable or parameter as final doesn't really do much and is rarely necessary. There are basically two reasons for it:

  1. Some developers believe that anything that doesn't need to be mutable should be immutable. While I agree in principle (immutability is a good thing in many respects), I think that for a language like Java, declaring everything final is going overboard.
  2. If your method contains a local or anonymous inner class and you want any of its local variables or parameters to be accessible to code in the inner class, you have to declare them final . This is a kluge in the Java language; its purpose is to prevent code in the inner class from trying to modify the variables or parameters after they are no longer alive.

They're final to the scope they're in. That's just the way it works.

I imagine the point of making them final in this instance is to prevent future developers from changing them when they shouldn't be changed. It's just defensive coding in this case.

对于基元和引用, final就像是const in c。

Readability


When it comes to local scope, I find that its usage is variable. That is, some programmers will elect to use it (and abuse it...like me) and some will use it sparingly (eg to ensure a class cannot be subclassed, immutability, and etc.).

I find that when working with a group of developers, it's either all, or nothing. Once you start including final modifiers in the local scope, you know that you're hooked and there's not much your team can do (except get you fired...somehow...for being an effective developer).

My perspective

It is a good practice (for better maintenance etc) to make the local variables as final. This is one way of reducing the side effects . Side-effect free code is easy to reason about and hence more readable and easy to maintain.

Overly religious programmers would tell you to mark final on local variables (including method parameters) whenver you can.

In practice nobody does that, including those programmers.

Don't bother.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM