java 最终关键字在 Android 中的工作原理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35301897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:59:06  来源:igfitidea点击:

How final keyword works in Android

javaandroidfinal

提问by Luiz Henrique Ugliano

I Know that in Java we use finalkeyword to variables or something else to make its values not to be changed.

我知道在 Java 中我们使用final关键字变量或其他东西来使其值不被更改。

What is the difference in using finalas in the example below?

final在下面的例子中使用有什么区别?

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

回答by logger

It is java...finalkey word is always the same either in android or not in android. It depends on what you apply to.

它是 java...final关键字在 android 或不在 android 中总是相同的。这取决于你申请的是什么。

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.

应用于该类,您不能覆盖该类。

回答by Raymond

Final only lock the reference. Not the object and method inside the reference.

最后只锁定引用。不是引用中的对象和方法。

In Android it's just like the way in Java.

在 Android 中,它就像在 Java 中一样。

For example, final int a = 5, then a cannot be changed.

例如,final int a = 5,则 a 不能更改。

Final final TextView campoTexto; then campoTexto cannot be redefined, but the method inside, like setText or others, are allowed to use.

最后final TextView campoTexto; 那么campoTexto 不能被重新定义,但是里面的方法,like setText or others, 是允许使用的。

A more comprehensive example is Final Deque<Integer> stack = new ArrayDeque<>();then stack cannot be redefined, but stack.push, popand other methods are allowed to use, so the object inside the stack are allowed to change

一个更全面的例子是Final Deque<Integer> stack = new ArrayDeque<>();stack 不能被重新定义,但是stack.push, pop和其他方法是允许使用的,所以 stack 里面的对象是允许改变的

回答by thyago stall

For variables, the finalkeyword 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 campoTextoagain, the compiler will throw an error out.

对于变量,final关键字意味着它基本上是一个常量。在这种情况下,由于它是一个对象,因此无法更改其引用。所以基本上如果你final TextView campoTexto再次尝试赋值,编译器会抛出一个错误。