0

Why can I refer to non-final fields from inside an inner class

public class Selection extends Activity {
     int con=0;

but not to non-final variables

public void loadlist() {               
     int con=0;

and I have to make the variable final instead?

public void loadlist() {
     final int con=0;

EDIT: If I want to declare an int inside a method, I need to make the int final. But that is not the case when I declare it outside (like in the first code block).

flup
  • 26,937
  • 7
  • 52
  • 74
いちにち
  • 417
  • 6
  • 16

3 Answers3

4

I think that you try to use con value inside of inner class. Try to read this article

Best wishes.

Yakiv Mospan
  • 8,174
  • 3
  • 31
  • 35
  • Thanks for the link, but since I've only recently started learning java, most of that is difficult for me to assimilate. Still, that is what I was looking for, thanks. – いちにち Jun 23 '13 at 14:05
0

Use this.con = 0 in your code. It will work

Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39
0

The java specs say

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

If you first create the inner class instance, then set the variable to another value, the inner class has no reference to the new value of the variable and would have no way of knowing what value to use.

So java demands make the variable final, i.e. promise not to change it. This makes life easy for the compiler. The current value of the variable can be copied and remembered when the inner class gets instantiated.

If you use a field, it remains accessable at all times since the inner class has a reference to the instance of the outer class it lives in. Even if the field changes, the inner class still can read it.

C# is less strict. There the inner class may read and write to all variables of the scope it was created in.

flup
  • 26,937
  • 7
  • 52
  • 74
  • See also http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen – flup Jun 24 '13 at 21:04