Luiz Henrique Ugliano
Luiz Henrique Ugliano

Reputation: 1317

How final keyword works in Android

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

Upvotes: 6

Views: 23504

Answers (3)

Raymond
Raymond

Reputation: 61

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

Upvotes: 6

thyago stall
thyago stall

Reputation: 1704

For variables, the final keyword means it is basically a constant. In this case, as it is an object, its reference cannot be changed. So basically if you try to assign to final TextView campoTexto again, the compiler will throw an error out.

Upvotes: 4

logger
logger

Reputation: 2053

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.

Upvotes: 28

Related Questions