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

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

java - What does "final" do if you place it before a variable?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...