Java和Final关键字的使用 [英] Java and the use of the Final keyword

查看:135
本文介绍了Java和Final关键字的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java新手,已经在Delphi和C#中编程了一段时间。我的问题涉及当变量声明和实例化都发生在同一方法的范围内时,变量上使用final关键字,该变量包含实例化类。例如

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;
}

好吧所以我认为我得到的事实是最终变量只能永远由于每个声明上的final关键字,被分配给一次并且无法更改,但是当方法退出时,这两个变量都不会超出范围吗?并再次调用该方法将简单地重新分配2个新的最终变量,这些变量在方法退出时将再次超出范围?

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?

对我来说,在这些变量上使用final关键字似乎有点奇怪?除非我不理解它们如何影响方法范围内的局部变量?

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 对范围没有影响。

它只是阻止变量重新分配。

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 是因为Java不支持真正的闭包,所以在匿名内部类中使用变量也是必需的。

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

这篇关于Java和Final关键字的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆