最终关键字如何在Android中运行

Lui*_*ano 4 java android final

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

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);
Run Code Online (Sandbox Code Playgroud)

log*_*ger 20

它是java ... final关键词在android中总是相同或者在android中都没有.这取决于你申请的内容.

例如

应用于变量意味着初始化后无法更改.

应用于方法意味着它不能重载方法.

应用于该类,您无法覆盖该类.


小智 6

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

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

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

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

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