I Know that in Java we use final
keyword to variables or something else to make its values not to be changed.
What is the difference in using final
as in the example below?
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView campoTexto = (TextView) findViewById(R.id.campoTexto);
Button botaoTexto = (Button) findViewById(R.id.botaoTexto);
Button botaoCor = (Button) findViewById(R.id.botaoCor);
final RelativeLayout fundoTela = (RelativeLayout) findViewById(R.id.fundoTela);
The final keyword is a non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override). The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The final keyword is called a "modifier".
Create Constants, prevent inheritance, and prevent methods from being inheritance are the three main uses of final keyword in java.
In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once. Once a final variable has been assigned, it always contains the same value.
It is java...final
key word is always the same either in android or not in android. It depends on what you apply to.
For example
Apply to the variable means it cannot be changed after initialized.
Apply to method means it cannot be overload the method.
Apply to the class and you cannot override that class.
Final only lock the reference. Not the object and method inside the reference.
In Android it's just like the way in Java.
For example, final int a = 5
, then a cannot be changed.
Final final TextView campoTexto
; then campoTexto cannot be redefined, but the method inside, like setText or others
, are allowed to use.
A more comprehensive example is Final Deque<Integer> stack = new ArrayDeque<>();
then stack cannot be redefined, but stack.push, pop
and other methods are allowed to use, so the object inside the stack are allowed to change
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