Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 207
Luiz Henrique Ugliano Avatar asked Feb 09 '16 20:02

Luiz Henrique Ugliano


People also ask

How is final keyword used?

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".

What are the three uses of final keyword explain with example?

Create Constants, prevent inheritance, and prevent methods from being inheritance are the three main uses of final keyword in java.

What is final in Java Android?

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.


2 Answers

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.

like image 182
logger Avatar answered Oct 04 '22 21:10

logger


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

like image 43
Raymond Avatar answered Oct 04 '22 20:10

Raymond