为什么说,"不能引用非最终变量我在一个不同的方法"?限定的内部类中 [英] Why it says that "Cannot refer to a non-final variable i inside an inner class defined in a different method"?

查看:209
本文介绍了为什么说,"不能引用非最终变量我在一个不同的方法"?限定的内部类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有按钮,点击监听,并在的onCreate()方法,我有一个像

I have button click listener and in onCreate() method I have a local variable like

 onCreate() {

 super.onCreate();

 int i = 10;

 Button button = (Button)findViewById(R.id.button);

 button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            i++;
        }   
    });

为什么java的要求让我最后?

Why java asks for to make me final ?

推荐答案

在的onCreate()方法返回时,局部变量将被从堆栈中清除,因此他们将不再存在。但匿名类对象的新View.OnClickListener()引用了这些变量。原因这是错误的行为,所以Java不允许你这样做。

When the onCreate() method returns, your local variable will be cleaned up from the stack, so they won't exist anymore. But the anonymous class object new View.OnClickListener() references these variables. Of cause it's wrong behavior so java don't allow you to do this.

在它是最终变成常数。因此被存储在堆中,可以安全地使用在匿名类

After it is final it becomes a constant. So it is storing in the heap and can be safely used in anonymous classes.

这篇关于为什么说,"不能引用非最终变量我在一个不同的方法"?限定的内部类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆