简体   繁体   中英

Type Cannot refer to a non-final variable Asortiment inside an inner class defined in a different method

I add simple class to my application:

public class Nomenklatura implements Serializable
    {
        private Boolean SmenaIsOpen=false;
        public Nomenklatura()
        {
            SmenaIsOpen=false;
        }
        public String OpenSmena()
        {
            SmenaIsOpen=true;
            return "ok";
        }
        public String CloseSmena()
        {
            return "ok";
        }
        public Boolean GetSmenaIsOen()
        {
            return SmenaIsOpen;
        }
        public void SetSmenaIsOen(Boolean val)
        {
            SmenaIsOpen=val;
        }

    }

Application should work with one object this class. When I use it in activity:

@Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.presmena);  
        Nomenklatura Asortiment;
         Asortiment=(Nomenklatura) getIntent().getExtras().getSerializable("Nomenklatura");
         Button but1=(Button) findViewById(R.id.button1);
            but1.setOnClickListener(new OnClickListener() 
            {
                @Override
                public void onClick(View arg0) 
                {
                    if(Asortiment.GetSmenaIsOen()) Asortiment.CloseSmena();
                    else Asortiment.OpenSmena();
                }
            });
    }

I get error: Cannot refer to a non-final variable Asortiment inside an inner class defined in a different method Presmena.java. Help to understand, what is wrong

您必须将Asortiment变量声明为final

final Nomenklatura Asortiment;

Declare it like this

final Nomenklatura Asortiment = ...

and it should work. When you declare inner classes and you make them use your local variables (which would normally be out of the inner scope, if you think about it), they need to be captured. In Java, you are required to mark such variables as final , to avoid unintended behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM