Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 874
Jack Love Avatar asked Oct 25 '10 02:10

Jack Love


People also ask

What does final do to a variable?

Final variables If a variable is declared with the final keyword, its value cannot be changed once initialized. Note that the variable does not necessarily have to be initialized at the time of declaration. If it's declared but not yet initialized, it's called a blank final variable.

What is the significance of final keyword used as modifier before a variable?

As mentioned previously, the final modifier prevents a method from being modified in a subclass. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

What does final do to a method?

You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .

What happens if the variable is final in Java?

Once any entity (variable, method or class) is declared final , it can be assigned only once. That is, the final variable cannot be reinitialized with another value. the final method cannot be overridden.


1 Answers

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.

like image 200
Andrew Swan Avatar answered Sep 22 '22 06:09

Andrew Swan