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?
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.
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.
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 .
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.
Short Answer
Stops the "myTextField" variable being assigned to something else.
Long Answer
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With