“最终”是什么如果你把它放在一个变量之前呢? [英] What does "final" do if you place it before a variable?

查看:87
本文介绍了“最终”是什么如果你把它放在一个变量之前呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常基本的问题,但是,如果你把它放在一个变量之前,那么最终会做什么呢...

Very basic question, but, what does "final" do if you place it before a variable such as below...

final EditText myTextField = (EditText) findViewById(R.id.myTextField);

final 做什么?

推荐答案

简答

停止myTextField 变量被分配给其他东西。

Stops the "myTextField" variable being assigned to something else.

长答案


  • 不会停止变形的myTextField变量,例如将其字段设置为新值。

  • 使代码更具可读性(恕我直言),因为读者永远不必怀疑以后是否会在代码中重新分配myTextField变量。

  • 防范变量意外重新分配的bug类别(使实例不可变的原因相同,只是规模较小)。

由于上面给出的原因,我总是将final修饰符应用于静态字段,实例字段,局部变量和方法参数。它确实使代码膨胀了一点,但对我来说,值得额外的可读性和稳健性。

For the reasons given above, I always apply the "final" modifier wherever I can to static fields, instance fields, local variables, and method parameters. It does bloat the code a little, but for me it's worth the extra readability and robustness.

这篇关于“最终”是什么如果你把它放在一个变量之前呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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