0
@Test
public void test() throws IOException{
    int a = 5;
    Pipe pipe = Pipe.open();
    new Thread(new Runnable(){
        @Override
        public void run() {
            pipe.sink();
            a++;
        }
    }).start();
}

why a++ reports an error :

Local variable a defined in an enclosing scope must be final or effectively final

but pipe.sink() doesn't ? i'm using jdk8.0

azro
  • 53,056
  • 7
  • 34
  • 70
ligen
  • 13
  • 3
  • 1
    You are not reassigning the value of `pipe`, so the variable is effectively final. – Andy Turner Jul 03 '17 at 12:47
  • because it has to... declare a as a class member.... – ΦXocę 웃 Пepeúpa ツ Jul 03 '17 at 12:47
  • This is a good explanation of your "WHY" https://stackoverflow.com/questions/11424753/why-do-variables-passed-to-runnable-need-to-be-final Hope it helps..!! – miiiii Jul 03 '17 at 12:51
  • thanks,i understand! – ligen Jul 03 '17 at 12:54
  • @ligen To be clear, "effectively final" means that the variable itself is not marked as `final`, but the compiler is smart enough to detect that the variable never changes in the code. (Note that in case of references only the reference *itself* is not changed, the members of the object might be changed.) – MC Emperor Jul 03 '17 at 14:08

0 Answers0