Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when you have final values and inner classes in a method?

I have came across many situation where I needed to pass value to an other thread and I founded out that I could do it this way, but I have been wondering how is it working ?

public void method() {
    final EventHandler handle = someReference;

    Thread thread = new Thread() {
        public void run() {
            handle.onEvent();
        }
    };

    thread.start();
}

Edit: Just realise my question wasn't exactly pointing toward what I wanted to know. It's more "how" it works rather then "why".

like image 850
HoLyVieR Avatar asked Jun 26 '10 20:06

HoLyVieR


2 Answers

Here's a longer explanation of HOW it works: http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/

like image 66
cristis Avatar answered Sep 19 '22 06:09

cristis


No method can access local variables of other methods. This includes methods of anonymous classes as the one in your example. That is, the run method in the anonymous Thread class, can not access the local variable of method().

Writing final in front of the local variable is a way for you as a programmer to let the compiler know that the variable actually can be treated as a value. Since this variable (read value!) will not change, it is "ok" to access it in other methods.

like image 26
aioobe Avatar answered Sep 20 '22 06:09

aioobe