This below code is from Dan's mock,anonymous class section.
Compile-time errors are generated at which lines?
The answer is 3 and 5.The explaination given by dan for this is :
Local method variables and method parameters are stored on the stack and go out of scope after the method is exited. Although a local reference variable is stored on the stack, the referenced object is stored on the heap; so the object can continue to exist long after the method runs to completion. An object that is instantiated within a method or block is not permitted to refer to a variable that is declared within the method or block unless the variable is declared final and "the variable declaration precedes the creation of the object".
Please find the double quoted sentence in the above para,Can anyone modify the code and show how the statement on line 6 can be coded so that it precedes the creation of object.
Joined: Aug 10, 2004
however dont confuse this behavir with standard initializers though.
Just to confirm, there was nothing wrong with line //6 from your code example. Variable l2 is final and it DOES precede creation of the object that is an anonymous inner class. The change to the code in the 1st response caused line 6 to fail to compile because the declaration of l2 DID NOT precede creation of the object (anonymous inner class).