Java and the use of the Final keyword

2019-03-31 04:26发布

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. e.g.

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?

8条回答
在下西门庆
2楼-- · 2019-03-31 05:19

final is like const in c for primitives and references.

查看更多
迷人小祖宗
3楼-- · 2019-03-31 05:23

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.
查看更多
登录 后发表回答