Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

What does final do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

Short Answer

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

Long Answer

  • Does NOT stop the "myTextField" variable being mutated, e.g. having its fields set to new values.
  • Makes code more readable (IMHO) because the reader never has to wonder whether the "myTextField" variable will be reassigned later on in the code.
  • Guards against the category of bug whereby variables are accidentally reassigned (same reasoning behind making instances immutable, only on a smaller scale).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...