Why are only final variables accessible in anonymous class?











up vote
311
down vote

favorite
182














  1. a can only be final here. Why? How can I reassign a in onClick() method without keeping it as private member?



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;

    }
    });
    }



  2. How can I return the 5 * a when it clicked? I mean,



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;
    return b; // but return type is void
    }
    });
    }











share|improve this question




















  • 1




    I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
    – Mehrdad
    Jan 19 '11 at 7:00






  • 4




    What are you trying to achieve? Click handler could be executed when "f" is finished.
    – Ivan Dubrov
    Jan 19 '11 at 7:02












  • @Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
    – user467871
    Jan 19 '11 at 7:08






  • 2




    That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
    – Mehrdad
    Jan 19 '11 at 7:10






  • 4




    Note: as of Java 8, your variable only needs to be effectively final
    – Peter Lawrey
    Feb 24 '16 at 12:41















up vote
311
down vote

favorite
182














  1. a can only be final here. Why? How can I reassign a in onClick() method without keeping it as private member?



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;

    }
    });
    }



  2. How can I return the 5 * a when it clicked? I mean,



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;
    return b; // but return type is void
    }
    });
    }











share|improve this question




















  • 1




    I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
    – Mehrdad
    Jan 19 '11 at 7:00






  • 4




    What are you trying to achieve? Click handler could be executed when "f" is finished.
    – Ivan Dubrov
    Jan 19 '11 at 7:02












  • @Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
    – user467871
    Jan 19 '11 at 7:08






  • 2




    That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
    – Mehrdad
    Jan 19 '11 at 7:10






  • 4




    Note: as of Java 8, your variable only needs to be effectively final
    – Peter Lawrey
    Feb 24 '16 at 12:41













up vote
311
down vote

favorite
182









up vote
311
down vote

favorite
182






182







  1. a can only be final here. Why? How can I reassign a in onClick() method without keeping it as private member?



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;

    }
    });
    }



  2. How can I return the 5 * a when it clicked? I mean,



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;
    return b; // but return type is void
    }
    });
    }











share|improve this question

















  1. a can only be final here. Why? How can I reassign a in onClick() method without keeping it as private member?



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;

    }
    });
    }



  2. How can I return the 5 * a when it clicked? I mean,



    private void f(Button b, final int a){
    b.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
    int b = a*5;
    return b; // but return type is void
    }
    });
    }








java event-handling anonymous-class






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 14 '17 at 9:29









Andrii Abramov

3,97642846




3,97642846










asked Jan 19 '11 at 6:58







user467871















  • 1




    I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
    – Mehrdad
    Jan 19 '11 at 7:00






  • 4




    What are you trying to achieve? Click handler could be executed when "f" is finished.
    – Ivan Dubrov
    Jan 19 '11 at 7:02












  • @Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
    – user467871
    Jan 19 '11 at 7:08






  • 2




    That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
    – Mehrdad
    Jan 19 '11 at 7:10






  • 4




    Note: as of Java 8, your variable only needs to be effectively final
    – Peter Lawrey
    Feb 24 '16 at 12:41














  • 1




    I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
    – Mehrdad
    Jan 19 '11 at 7:00






  • 4




    What are you trying to achieve? Click handler could be executed when "f" is finished.
    – Ivan Dubrov
    Jan 19 '11 at 7:02












  • @Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
    – user467871
    Jan 19 '11 at 7:08






  • 2




    That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
    – Mehrdad
    Jan 19 '11 at 7:10






  • 4




    Note: as of Java 8, your variable only needs to be effectively final
    – Peter Lawrey
    Feb 24 '16 at 12:41








1




1




I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
– Mehrdad
Jan 19 '11 at 7:00




I don't think that Java anonymous classes provide the kind of lambda closure that you'd expect, but someone please correct me if I'm wrong...
– Mehrdad
Jan 19 '11 at 7:00




4




4




What are you trying to achieve? Click handler could be executed when "f" is finished.
– Ivan Dubrov
Jan 19 '11 at 7:02






What are you trying to achieve? Click handler could be executed when "f" is finished.
– Ivan Dubrov
Jan 19 '11 at 7:02














@Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
– user467871
Jan 19 '11 at 7:08




@Lambert if you want to use a in the onClick method it have to be final @Ivan how can f() method behaves like onClick() method return int when clicked
– user467871
Jan 19 '11 at 7:08




2




2




That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
– Mehrdad
Jan 19 '11 at 7:10




That's what I mean -- it doesn't support full closure because it doesn't allow access to non-final variables.
– Mehrdad
Jan 19 '11 at 7:10




4




4




Note: as of Java 8, your variable only needs to be effectively final
– Peter Lawrey
Feb 24 '16 at 12:41




Note: as of Java 8, your variable only needs to be effectively final
– Peter Lawrey
Feb 24 '16 at 12:41












13 Answers
13






active

oldest

votes

















up vote
442
down vote



accepted










As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.





It's basically due to the way Java manages closures.



When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)



As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.



Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.



If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)






share|improve this answer



















  • 2




    Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
    – Ivan Dubrov
    Jan 19 '11 at 7:14








  • 4




    @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
    – Jon Skeet
    Jan 19 '11 at 7:15






  • 1




    @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
    – Jon Skeet
    Sep 16 '11 at 21:07






  • 10




    This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
    – Mathias Bader
    Oct 24 '14 at 14:41






  • 16




    @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
    – Thilo
    Mar 4 '16 at 7:56


















up vote
40
down vote













There is a trick that allows anonymous class to update data in the outer scope.



private void f(Button b, final int a) {
final int res = new int[1];
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
res[0] = a * 5;
}
});

// But at this point handler is most likely not executed yet!
// How should we now res[0] is ready?
}


However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated



This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:



// ...

final int res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);

// ...





share|improve this answer



















  • 2




    thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
    – user467871
    Jan 19 '11 at 7:10






  • 5




    The answer then is that is how they are implemented :)
    – Ivan Dubrov
    Jan 19 '11 at 7:12






  • 1




    Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
    – RuntimeException
    Oct 30 '15 at 11:54












  • Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
    – lcn
    Dec 8 '15 at 23:24






  • 2




    You may also use e.g. AtomicReference or AtomicInt for the same purpose...
    – csharpfolk
    Aug 6 '17 at 12:35


















up vote
16
down vote













An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):




Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.




I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.



(Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)






share|improve this answer






























    up vote
    10
    down vote













    You can create a class level variable to get returned value. I mean



    class A {
    int k = 0;
    private void f(Button b, int a){
    b.addClickHandler(new ClickHandler() {
    @Override
    public void onClick(ClickEvent event) {
    k = a * 5;
    }
    });
    }


    now you can get value of K and use it where you want.



    Answer of your why is :



    A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).



    Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)






    share|improve this answer























    • I mentioned that "without keeping it as private member"
      – user467871
      Jan 19 '11 at 7:11


















    up vote
    7
    down vote













    Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like



    public class Test
    {
    public final int a = 3;


    or as a local variable, like



    public static void main(String args)
    {
    final int a = 3;


    If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.



    public class Test
    {
    public int a;
    public void doSomething()
    {
    Runnable runnable =
    new Runnable()
    {
    public void run()
    {
    System.out.println(a);
    a = a+1;
    }
    };
    }
    }


    You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.



    And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).



    It just copies over the value of a into an implicit int called a in your anonymous class.






    share|improve this answer

















    • 3




      I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
      – eljenso
      Jan 19 '11 at 12:23






    • 1




      well, I used class-level because the technique would work with both instance and static variables.
      – Zach L
      Jan 19 '11 at 17:01


















    up vote
    5
    down vote













    The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.






    share|improve this answer





















    • This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
      – Mike76
      Aug 27 '16 at 13:13












    • Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
      – Adowrath
      Sep 15 '17 at 7:30


















    up vote
    2
    down vote













    Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.






    share|improve this answer




























      up vote
      2
      down vote













      When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.



      (http://en.wikipedia.org/wiki/Final_%28Java%29)






      share|improve this answer




























        up vote
        1
        down vote













        private void f(Button b, final int a) {

        b.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
        a[0] = a[0] * 5;

        }
        });
        }





        share|improve this answer






























          up vote
          0
          down vote













          As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.



          Consider the use case where your lambdas instead of being apply, is stored in some place and run later.



          I remember that in Smalltalk you would get an illegal store raised when you do such modification.






          share|improve this answer




























            up vote
            0
            down vote













            Try this code,



            Create Array List and put value inside that and return it :



            private ArrayList f(Button b, final int a)
            {
            final ArrayList al = new ArrayList();
            b.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
            int b = a*5;
            al.add(b);
            }
            });
            return al;
            }





            share|improve this answer























            • OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
              – NitinSingh
              Jul 18 at 10:21


















            up vote
            0
            down vote













            To understand the rationale for this restriction, consider the following program:



            public class Program {

            interface Interface {
            public void printInteger();
            }
            static Interface interfaceInstance = null;

            static void initialize(int val) {
            class Class implements interface {
            @Override
            public void printInteger() {
            System.out.println(val);
            }
            }
            interfaceInstance = new Class();
            }

            public static void main(String args) {
            initialize(12345);
            interfaceInstance.printInteger();
            }
            }


            The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.






            share|improve this answer




























              up vote
              -2
              down vote













              Maybe this trick gives u an idea



              Boolean var= new anonymousClass(){
              private String myVar; //String for example
              @Overriden public Boolean method(int i){
              //use myVar and i
              }
              public String setVar(String var){myVar=var; return this;} //Returns self instane
              }.setVar("Hello").method(3);





              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4732544%2fwhy-are-only-final-variables-accessible-in-anonymous-class%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown
























                13 Answers
                13






                active

                oldest

                votes








                13 Answers
                13






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                442
                down vote



                accepted










                As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.





                It's basically due to the way Java manages closures.



                When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)



                As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.



                Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.



                If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)






                share|improve this answer



















                • 2




                  Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                  – Ivan Dubrov
                  Jan 19 '11 at 7:14








                • 4




                  @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                  – Jon Skeet
                  Jan 19 '11 at 7:15






                • 1




                  @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                  – Jon Skeet
                  Sep 16 '11 at 21:07






                • 10




                  This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                  – Mathias Bader
                  Oct 24 '14 at 14:41






                • 16




                  @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                  – Thilo
                  Mar 4 '16 at 7:56















                up vote
                442
                down vote



                accepted










                As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.





                It's basically due to the way Java manages closures.



                When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)



                As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.



                Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.



                If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)






                share|improve this answer



















                • 2




                  Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                  – Ivan Dubrov
                  Jan 19 '11 at 7:14








                • 4




                  @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                  – Jon Skeet
                  Jan 19 '11 at 7:15






                • 1




                  @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                  – Jon Skeet
                  Sep 16 '11 at 21:07






                • 10




                  This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                  – Mathias Bader
                  Oct 24 '14 at 14:41






                • 16




                  @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                  – Thilo
                  Mar 4 '16 at 7:56













                up vote
                442
                down vote



                accepted







                up vote
                442
                down vote



                accepted






                As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.





                It's basically due to the way Java manages closures.



                When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)



                As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.



                Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.



                If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)






                share|improve this answer














                As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.





                It's basically due to the way Java manages closures.



                When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)



                As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.



                Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.



                If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 4 '16 at 8:00

























                answered Jan 19 '11 at 7:10









                Jon Skeet

                1067k66778258366




                1067k66778258366








                • 2




                  Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                  – Ivan Dubrov
                  Jan 19 '11 at 7:14








                • 4




                  @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                  – Jon Skeet
                  Jan 19 '11 at 7:15






                • 1




                  @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                  – Jon Skeet
                  Sep 16 '11 at 21:07






                • 10




                  This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                  – Mathias Bader
                  Oct 24 '14 at 14:41






                • 16




                  @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                  – Thilo
                  Mar 4 '16 at 7:56














                • 2




                  Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                  – Ivan Dubrov
                  Jan 19 '11 at 7:14








                • 4




                  @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                  – Jon Skeet
                  Jan 19 '11 at 7:15






                • 1




                  @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                  – Jon Skeet
                  Sep 16 '11 at 21:07






                • 10




                  This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                  – Mathias Bader
                  Oct 24 '14 at 14:41






                • 16




                  @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                  – Thilo
                  Mar 4 '16 at 7:56








                2




                2




                Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                – Ivan Dubrov
                Jan 19 '11 at 7:14






                Yeah. Basically, full closures support could be implemented by moving all variables that are referenced in a special auto-generated class.
                – Ivan Dubrov
                Jan 19 '11 at 7:14






                4




                4




                @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                – Jon Skeet
                Jan 19 '11 at 7:15




                @Ivan: Like C#, basically. It comes with a fair degree of complexity though, if you want the same sort of functionality as C# where variables from different scopes can be "instantiated" different numbers of times.
                – Jon Skeet
                Jan 19 '11 at 7:15




                1




                1




                @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                – Jon Skeet
                Sep 16 '11 at 21:07




                @Ustaman: I suspect you could - but it's a bit too much to go into in comments. I suggest you ask a new question with some sample code.
                – Jon Skeet
                Sep 16 '11 at 21:07




                10




                10




                This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                – Mathias Bader
                Oct 24 '14 at 14:41




                This was all true for Java 7, keep in mind that with Java 8, closures have been introduced and now it is indeed possible to access a non-final field of a class from its inner class.
                – Mathias Bader
                Oct 24 '14 at 14:41




                16




                16




                @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                – Thilo
                Mar 4 '16 at 7:56




                @MathiasBader: Really? I thought it is still essentially the same mechanism, the compiler is now just clever enough to infer final (but it still needs to be effectively final).
                – Thilo
                Mar 4 '16 at 7:56












                up vote
                40
                down vote













                There is a trick that allows anonymous class to update data in the outer scope.



                private void f(Button b, final int a) {
                final int res = new int[1];
                b.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                res[0] = a * 5;
                }
                });

                // But at this point handler is most likely not executed yet!
                // How should we now res[0] is ready?
                }


                However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated



                This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:



                // ...

                final int res = new int[1];
                Runnable r = new Runnable() { public void run() { res[0] = 123; } };
                r.run();
                System.out.println(res[0]);

                // ...





                share|improve this answer



















                • 2




                  thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                  – user467871
                  Jan 19 '11 at 7:10






                • 5




                  The answer then is that is how they are implemented :)
                  – Ivan Dubrov
                  Jan 19 '11 at 7:12






                • 1




                  Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                  – RuntimeException
                  Oct 30 '15 at 11:54












                • Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                  – lcn
                  Dec 8 '15 at 23:24






                • 2




                  You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                  – csharpfolk
                  Aug 6 '17 at 12:35















                up vote
                40
                down vote













                There is a trick that allows anonymous class to update data in the outer scope.



                private void f(Button b, final int a) {
                final int res = new int[1];
                b.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                res[0] = a * 5;
                }
                });

                // But at this point handler is most likely not executed yet!
                // How should we now res[0] is ready?
                }


                However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated



                This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:



                // ...

                final int res = new int[1];
                Runnable r = new Runnable() { public void run() { res[0] = 123; } };
                r.run();
                System.out.println(res[0]);

                // ...





                share|improve this answer



















                • 2




                  thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                  – user467871
                  Jan 19 '11 at 7:10






                • 5




                  The answer then is that is how they are implemented :)
                  – Ivan Dubrov
                  Jan 19 '11 at 7:12






                • 1




                  Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                  – RuntimeException
                  Oct 30 '15 at 11:54












                • Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                  – lcn
                  Dec 8 '15 at 23:24






                • 2




                  You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                  – csharpfolk
                  Aug 6 '17 at 12:35













                up vote
                40
                down vote










                up vote
                40
                down vote









                There is a trick that allows anonymous class to update data in the outer scope.



                private void f(Button b, final int a) {
                final int res = new int[1];
                b.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                res[0] = a * 5;
                }
                });

                // But at this point handler is most likely not executed yet!
                // How should we now res[0] is ready?
                }


                However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated



                This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:



                // ...

                final int res = new int[1];
                Runnable r = new Runnable() { public void run() { res[0] = 123; } };
                r.run();
                System.out.println(res[0]);

                // ...





                share|improve this answer














                There is a trick that allows anonymous class to update data in the outer scope.



                private void f(Button b, final int a) {
                final int res = new int[1];
                b.addClickHandler(new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                res[0] = a * 5;
                }
                });

                // But at this point handler is most likely not executed yet!
                // How should we now res[0] is ready?
                }


                However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated



                This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:



                // ...

                final int res = new int[1];
                Runnable r = new Runnable() { public void run() { res[0] = 123; } };
                r.run();
                System.out.println(res[0]);

                // ...






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jul 14 '17 at 9:29









                Andrii Abramov

                3,97642846




                3,97642846










                answered Jan 19 '11 at 7:06









                Ivan Dubrov

                3,82622438




                3,82622438








                • 2




                  thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                  – user467871
                  Jan 19 '11 at 7:10






                • 5




                  The answer then is that is how they are implemented :)
                  – Ivan Dubrov
                  Jan 19 '11 at 7:12






                • 1




                  Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                  – RuntimeException
                  Oct 30 '15 at 11:54












                • Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                  – lcn
                  Dec 8 '15 at 23:24






                • 2




                  You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                  – csharpfolk
                  Aug 6 '17 at 12:35














                • 2




                  thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                  – user467871
                  Jan 19 '11 at 7:10






                • 5




                  The answer then is that is how they are implemented :)
                  – Ivan Dubrov
                  Jan 19 '11 at 7:12






                • 1




                  Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                  – RuntimeException
                  Oct 30 '15 at 11:54












                • Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                  – lcn
                  Dec 8 '15 at 23:24






                • 2




                  You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                  – csharpfolk
                  Aug 6 '17 at 12:35








                2




                2




                thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                – user467871
                Jan 19 '11 at 7:10




                thanks for your answer. I know all of this and my solution is better than this. my question is "why only final" ?
                – user467871
                Jan 19 '11 at 7:10




                5




                5




                The answer then is that is how they are implemented :)
                – Ivan Dubrov
                Jan 19 '11 at 7:12




                The answer then is that is how they are implemented :)
                – Ivan Dubrov
                Jan 19 '11 at 7:12




                1




                1




                Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                – RuntimeException
                Oct 30 '15 at 11:54






                Thanks. I had used the trick above on my own. I was not sure if it is a good idea. If Java does not allow it, there might be a good reason. Your answer clarifies that my List.forEach code is safe.
                – RuntimeException
                Oct 30 '15 at 11:54














                Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                – lcn
                Dec 8 '15 at 23:24




                Read stackoverflow.com/q/12830611/2073130 for a good discussion of the rationale behind "why only final".
                – lcn
                Dec 8 '15 at 23:24




                2




                2




                You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                – csharpfolk
                Aug 6 '17 at 12:35




                You may also use e.g. AtomicReference or AtomicInt for the same purpose...
                – csharpfolk
                Aug 6 '17 at 12:35










                up vote
                16
                down vote













                An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):




                Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.




                I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.



                (Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)






                share|improve this answer



























                  up vote
                  16
                  down vote













                  An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):




                  Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.




                  I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.



                  (Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)






                  share|improve this answer

























                    up vote
                    16
                    down vote










                    up vote
                    16
                    down vote









                    An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):




                    Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.




                    I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.



                    (Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)






                    share|improve this answer














                    An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):




                    Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.




                    I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.



                    (Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 23 '17 at 12:10









                    Community

                    11




                    11










                    answered Jan 19 '11 at 7:29









                    Andreas_D

                    94.6k11142230




                    94.6k11142230






















                        up vote
                        10
                        down vote













                        You can create a class level variable to get returned value. I mean



                        class A {
                        int k = 0;
                        private void f(Button b, int a){
                        b.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                        k = a * 5;
                        }
                        });
                        }


                        now you can get value of K and use it where you want.



                        Answer of your why is :



                        A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).



                        Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)






                        share|improve this answer























                        • I mentioned that "without keeping it as private member"
                          – user467871
                          Jan 19 '11 at 7:11















                        up vote
                        10
                        down vote













                        You can create a class level variable to get returned value. I mean



                        class A {
                        int k = 0;
                        private void f(Button b, int a){
                        b.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                        k = a * 5;
                        }
                        });
                        }


                        now you can get value of K and use it where you want.



                        Answer of your why is :



                        A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).



                        Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)






                        share|improve this answer























                        • I mentioned that "without keeping it as private member"
                          – user467871
                          Jan 19 '11 at 7:11













                        up vote
                        10
                        down vote










                        up vote
                        10
                        down vote









                        You can create a class level variable to get returned value. I mean



                        class A {
                        int k = 0;
                        private void f(Button b, int a){
                        b.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                        k = a * 5;
                        }
                        });
                        }


                        now you can get value of K and use it where you want.



                        Answer of your why is :



                        A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).



                        Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)






                        share|improve this answer














                        You can create a class level variable to get returned value. I mean



                        class A {
                        int k = 0;
                        private void f(Button b, int a){
                        b.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                        k = a * 5;
                        }
                        });
                        }


                        now you can get value of K and use it where you want.



                        Answer of your why is :



                        A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).



                        Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jul 14 '17 at 9:30









                        Andrii Abramov

                        3,97642846




                        3,97642846










                        answered Jan 19 '11 at 7:09









                        Ashfak Balooch

                        1,64431729




                        1,64431729












                        • I mentioned that "without keeping it as private member"
                          – user467871
                          Jan 19 '11 at 7:11


















                        • I mentioned that "without keeping it as private member"
                          – user467871
                          Jan 19 '11 at 7:11
















                        I mentioned that "without keeping it as private member"
                        – user467871
                        Jan 19 '11 at 7:11




                        I mentioned that "without keeping it as private member"
                        – user467871
                        Jan 19 '11 at 7:11










                        up vote
                        7
                        down vote













                        Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like



                        public class Test
                        {
                        public final int a = 3;


                        or as a local variable, like



                        public static void main(String args)
                        {
                        final int a = 3;


                        If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.



                        public class Test
                        {
                        public int a;
                        public void doSomething()
                        {
                        Runnable runnable =
                        new Runnable()
                        {
                        public void run()
                        {
                        System.out.println(a);
                        a = a+1;
                        }
                        };
                        }
                        }


                        You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.



                        And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).



                        It just copies over the value of a into an implicit int called a in your anonymous class.






                        share|improve this answer

















                        • 3




                          I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                          – eljenso
                          Jan 19 '11 at 12:23






                        • 1




                          well, I used class-level because the technique would work with both instance and static variables.
                          – Zach L
                          Jan 19 '11 at 17:01















                        up vote
                        7
                        down vote













                        Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like



                        public class Test
                        {
                        public final int a = 3;


                        or as a local variable, like



                        public static void main(String args)
                        {
                        final int a = 3;


                        If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.



                        public class Test
                        {
                        public int a;
                        public void doSomething()
                        {
                        Runnable runnable =
                        new Runnable()
                        {
                        public void run()
                        {
                        System.out.println(a);
                        a = a+1;
                        }
                        };
                        }
                        }


                        You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.



                        And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).



                        It just copies over the value of a into an implicit int called a in your anonymous class.






                        share|improve this answer

















                        • 3




                          I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                          – eljenso
                          Jan 19 '11 at 12:23






                        • 1




                          well, I used class-level because the technique would work with both instance and static variables.
                          – Zach L
                          Jan 19 '11 at 17:01













                        up vote
                        7
                        down vote










                        up vote
                        7
                        down vote









                        Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like



                        public class Test
                        {
                        public final int a = 3;


                        or as a local variable, like



                        public static void main(String args)
                        {
                        final int a = 3;


                        If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.



                        public class Test
                        {
                        public int a;
                        public void doSomething()
                        {
                        Runnable runnable =
                        new Runnable()
                        {
                        public void run()
                        {
                        System.out.println(a);
                        a = a+1;
                        }
                        };
                        }
                        }


                        You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.



                        And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).



                        It just copies over the value of a into an implicit int called a in your anonymous class.






                        share|improve this answer












                        Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like



                        public class Test
                        {
                        public final int a = 3;


                        or as a local variable, like



                        public static void main(String args)
                        {
                        final int a = 3;


                        If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.



                        public class Test
                        {
                        public int a;
                        public void doSomething()
                        {
                        Runnable runnable =
                        new Runnable()
                        {
                        public void run()
                        {
                        System.out.println(a);
                        a = a+1;
                        }
                        };
                        }
                        }


                        You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.



                        And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).



                        It just copies over the value of a into an implicit int called a in your anonymous class.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 19 '11 at 7:22









                        Zach L

                        13.2k33136




                        13.2k33136








                        • 3




                          I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                          – eljenso
                          Jan 19 '11 at 12:23






                        • 1




                          well, I used class-level because the technique would work with both instance and static variables.
                          – Zach L
                          Jan 19 '11 at 17:01














                        • 3




                          I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                          – eljenso
                          Jan 19 '11 at 12:23






                        • 1




                          well, I used class-level because the technique would work with both instance and static variables.
                          – Zach L
                          Jan 19 '11 at 17:01








                        3




                        3




                        I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                        – eljenso
                        Jan 19 '11 at 12:23




                        I associate "class-level variable" with static. Maybe it is more clear if you use "instance variable" instead.
                        – eljenso
                        Jan 19 '11 at 12:23




                        1




                        1




                        well, I used class-level because the technique would work with both instance and static variables.
                        – Zach L
                        Jan 19 '11 at 17:01




                        well, I used class-level because the technique would work with both instance and static variables.
                        – Zach L
                        Jan 19 '11 at 17:01










                        up vote
                        5
                        down vote













                        The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.






                        share|improve this answer





















                        • This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                          – Mike76
                          Aug 27 '16 at 13:13












                        • Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                          – Adowrath
                          Sep 15 '17 at 7:30















                        up vote
                        5
                        down vote













                        The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.






                        share|improve this answer





















                        • This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                          – Mike76
                          Aug 27 '16 at 13:13












                        • Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                          – Adowrath
                          Sep 15 '17 at 7:30













                        up vote
                        5
                        down vote










                        up vote
                        5
                        down vote









                        The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.






                        share|improve this answer












                        The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 1 '13 at 5:41









                        Swapnil Gangrade

                        179211




                        179211












                        • This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                          – Mike76
                          Aug 27 '16 at 13:13












                        • Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                          – Adowrath
                          Sep 15 '17 at 7:30


















                        • This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                          – Mike76
                          Aug 27 '16 at 13:13












                        • Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                          – Adowrath
                          Sep 15 '17 at 7:30
















                        This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                        – Mike76
                        Aug 27 '16 at 13:13






                        This is not how it is implemented in languages like C# that support this feature. In fact, the compiler changes the variable from a local variable to an instance variable, or it creates an extra data structure for these variables that can outlife the scope of the outer class. However, there are no "multiple copies of local variables"
                        – Mike76
                        Aug 27 '16 at 13:13














                        Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                        – Adowrath
                        Sep 15 '17 at 7:30




                        Mike76 I haven't had a look at C#'s implementation, but Scala does the second thing you mentioned I think: If an Int is being reassigned to inside a closure, change that variable to an instance of IntRef (essentially a mutable Integer wrapper). Every variable access is then rewritten accordingly.
                        – Adowrath
                        Sep 15 '17 at 7:30










                        up vote
                        2
                        down vote













                        Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.






                        share|improve this answer

























                          up vote
                          2
                          down vote













                          Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.






                          share|improve this answer























                            up vote
                            2
                            down vote










                            up vote
                            2
                            down vote









                            Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.






                            share|improve this answer












                            Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 19 '11 at 7:12









                            S73417H

                            1,92921733




                            1,92921733






















                                up vote
                                2
                                down vote













                                When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.



                                (http://en.wikipedia.org/wiki/Final_%28Java%29)






                                share|improve this answer

























                                  up vote
                                  2
                                  down vote













                                  When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.



                                  (http://en.wikipedia.org/wiki/Final_%28Java%29)






                                  share|improve this answer























                                    up vote
                                    2
                                    down vote










                                    up vote
                                    2
                                    down vote









                                    When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.



                                    (http://en.wikipedia.org/wiki/Final_%28Java%29)






                                    share|improve this answer












                                    When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.



                                    (http://en.wikipedia.org/wiki/Final_%28Java%29)







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Feb 17 '15 at 12:20









                                    ola_star

                                    211




                                    211






















                                        up vote
                                        1
                                        down vote













                                        private void f(Button b, final int a) {

                                        b.addClickHandler(new ClickHandler() {

                                        @Override
                                        public void onClick(ClickEvent event) {
                                        a[0] = a[0] * 5;

                                        }
                                        });
                                        }





                                        share|improve this answer



























                                          up vote
                                          1
                                          down vote













                                          private void f(Button b, final int a) {

                                          b.addClickHandler(new ClickHandler() {

                                          @Override
                                          public void onClick(ClickEvent event) {
                                          a[0] = a[0] * 5;

                                          }
                                          });
                                          }





                                          share|improve this answer

























                                            up vote
                                            1
                                            down vote










                                            up vote
                                            1
                                            down vote









                                            private void f(Button b, final int a) {

                                            b.addClickHandler(new ClickHandler() {

                                            @Override
                                            public void onClick(ClickEvent event) {
                                            a[0] = a[0] * 5;

                                            }
                                            });
                                            }





                                            share|improve this answer














                                            private void f(Button b, final int a) {

                                            b.addClickHandler(new ClickHandler() {

                                            @Override
                                            public void onClick(ClickEvent event) {
                                            a[0] = a[0] * 5;

                                            }
                                            });
                                            }






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Aug 28 '11 at 19:38









                                            Bo Persson

                                            77.1k15114181




                                            77.1k15114181










                                            answered Aug 28 '11 at 8:07









                                            Bruce Zu

                                            15212




                                            15212






















                                                up vote
                                                0
                                                down vote













                                                As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.



                                                Consider the use case where your lambdas instead of being apply, is stored in some place and run later.



                                                I remember that in Smalltalk you would get an illegal store raised when you do such modification.






                                                share|improve this answer

























                                                  up vote
                                                  0
                                                  down vote













                                                  As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.



                                                  Consider the use case where your lambdas instead of being apply, is stored in some place and run later.



                                                  I remember that in Smalltalk you would get an illegal store raised when you do such modification.






                                                  share|improve this answer























                                                    up vote
                                                    0
                                                    down vote










                                                    up vote
                                                    0
                                                    down vote









                                                    As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.



                                                    Consider the use case where your lambdas instead of being apply, is stored in some place and run later.



                                                    I remember that in Smalltalk you would get an illegal store raised when you do such modification.






                                                    share|improve this answer












                                                    As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.



                                                    Consider the use case where your lambdas instead of being apply, is stored in some place and run later.



                                                    I remember that in Smalltalk you would get an illegal store raised when you do such modification.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Jul 24 '17 at 13:41









                                                    mathk

                                                    4,61743261




                                                    4,61743261






















                                                        up vote
                                                        0
                                                        down vote













                                                        Try this code,



                                                        Create Array List and put value inside that and return it :



                                                        private ArrayList f(Button b, final int a)
                                                        {
                                                        final ArrayList al = new ArrayList();
                                                        b.addClickHandler(new ClickHandler() {

                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                        int b = a*5;
                                                        al.add(b);
                                                        }
                                                        });
                                                        return al;
                                                        }





                                                        share|improve this answer























                                                        • OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                          – NitinSingh
                                                          Jul 18 at 10:21















                                                        up vote
                                                        0
                                                        down vote













                                                        Try this code,



                                                        Create Array List and put value inside that and return it :



                                                        private ArrayList f(Button b, final int a)
                                                        {
                                                        final ArrayList al = new ArrayList();
                                                        b.addClickHandler(new ClickHandler() {

                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                        int b = a*5;
                                                        al.add(b);
                                                        }
                                                        });
                                                        return al;
                                                        }





                                                        share|improve this answer























                                                        • OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                          – NitinSingh
                                                          Jul 18 at 10:21













                                                        up vote
                                                        0
                                                        down vote










                                                        up vote
                                                        0
                                                        down vote









                                                        Try this code,



                                                        Create Array List and put value inside that and return it :



                                                        private ArrayList f(Button b, final int a)
                                                        {
                                                        final ArrayList al = new ArrayList();
                                                        b.addClickHandler(new ClickHandler() {

                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                        int b = a*5;
                                                        al.add(b);
                                                        }
                                                        });
                                                        return al;
                                                        }





                                                        share|improve this answer














                                                        Try this code,



                                                        Create Array List and put value inside that and return it :



                                                        private ArrayList f(Button b, final int a)
                                                        {
                                                        final ArrayList al = new ArrayList();
                                                        b.addClickHandler(new ClickHandler() {

                                                        @Override
                                                        public void onClick(ClickEvent event) {
                                                        int b = a*5;
                                                        al.add(b);
                                                        }
                                                        });
                                                        return al;
                                                        }






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Jul 18 at 11:00









                                                        Jouby

                                                        8831723




                                                        8831723










                                                        answered Jul 18 at 9:48









                                                        Wasim

                                                        1




                                                        1












                                                        • OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                          – NitinSingh
                                                          Jul 18 at 10:21


















                                                        • OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                          – NitinSingh
                                                          Jul 18 at 10:21
















                                                        OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                        – NitinSingh
                                                        Jul 18 at 10:21




                                                        OP is asking for reasons as to why something is required. Hence you should point out how your code is addressing it
                                                        – NitinSingh
                                                        Jul 18 at 10:21










                                                        up vote
                                                        0
                                                        down vote













                                                        To understand the rationale for this restriction, consider the following program:



                                                        public class Program {

                                                        interface Interface {
                                                        public void printInteger();
                                                        }
                                                        static Interface interfaceInstance = null;

                                                        static void initialize(int val) {
                                                        class Class implements interface {
                                                        @Override
                                                        public void printInteger() {
                                                        System.out.println(val);
                                                        }
                                                        }
                                                        interfaceInstance = new Class();
                                                        }

                                                        public static void main(String args) {
                                                        initialize(12345);
                                                        interfaceInstance.printInteger();
                                                        }
                                                        }


                                                        The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.






                                                        share|improve this answer

























                                                          up vote
                                                          0
                                                          down vote













                                                          To understand the rationale for this restriction, consider the following program:



                                                          public class Program {

                                                          interface Interface {
                                                          public void printInteger();
                                                          }
                                                          static Interface interfaceInstance = null;

                                                          static void initialize(int val) {
                                                          class Class implements interface {
                                                          @Override
                                                          public void printInteger() {
                                                          System.out.println(val);
                                                          }
                                                          }
                                                          interfaceInstance = new Class();
                                                          }

                                                          public static void main(String args) {
                                                          initialize(12345);
                                                          interfaceInstance.printInteger();
                                                          }
                                                          }


                                                          The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.






                                                          share|improve this answer























                                                            up vote
                                                            0
                                                            down vote










                                                            up vote
                                                            0
                                                            down vote









                                                            To understand the rationale for this restriction, consider the following program:



                                                            public class Program {

                                                            interface Interface {
                                                            public void printInteger();
                                                            }
                                                            static Interface interfaceInstance = null;

                                                            static void initialize(int val) {
                                                            class Class implements interface {
                                                            @Override
                                                            public void printInteger() {
                                                            System.out.println(val);
                                                            }
                                                            }
                                                            interfaceInstance = new Class();
                                                            }

                                                            public static void main(String args) {
                                                            initialize(12345);
                                                            interfaceInstance.printInteger();
                                                            }
                                                            }


                                                            The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.






                                                            share|improve this answer












                                                            To understand the rationale for this restriction, consider the following program:



                                                            public class Program {

                                                            interface Interface {
                                                            public void printInteger();
                                                            }
                                                            static Interface interfaceInstance = null;

                                                            static void initialize(int val) {
                                                            class Class implements interface {
                                                            @Override
                                                            public void printInteger() {
                                                            System.out.println(val);
                                                            }
                                                            }
                                                            interfaceInstance = new Class();
                                                            }

                                                            public static void main(String args) {
                                                            initialize(12345);
                                                            interfaceInstance.printInteger();
                                                            }
                                                            }


                                                            The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Nov 10 at 19:14









                                                            Benjamin Curtis Drake

                                                            212




                                                            212






















                                                                up vote
                                                                -2
                                                                down vote













                                                                Maybe this trick gives u an idea



                                                                Boolean var= new anonymousClass(){
                                                                private String myVar; //String for example
                                                                @Overriden public Boolean method(int i){
                                                                //use myVar and i
                                                                }
                                                                public String setVar(String var){myVar=var; return this;} //Returns self instane
                                                                }.setVar("Hello").method(3);





                                                                share|improve this answer

























                                                                  up vote
                                                                  -2
                                                                  down vote













                                                                  Maybe this trick gives u an idea



                                                                  Boolean var= new anonymousClass(){
                                                                  private String myVar; //String for example
                                                                  @Overriden public Boolean method(int i){
                                                                  //use myVar and i
                                                                  }
                                                                  public String setVar(String var){myVar=var; return this;} //Returns self instane
                                                                  }.setVar("Hello").method(3);





                                                                  share|improve this answer























                                                                    up vote
                                                                    -2
                                                                    down vote










                                                                    up vote
                                                                    -2
                                                                    down vote









                                                                    Maybe this trick gives u an idea



                                                                    Boolean var= new anonymousClass(){
                                                                    private String myVar; //String for example
                                                                    @Overriden public Boolean method(int i){
                                                                    //use myVar and i
                                                                    }
                                                                    public String setVar(String var){myVar=var; return this;} //Returns self instane
                                                                    }.setVar("Hello").method(3);





                                                                    share|improve this answer












                                                                    Maybe this trick gives u an idea



                                                                    Boolean var= new anonymousClass(){
                                                                    private String myVar; //String for example
                                                                    @Overriden public Boolean method(int i){
                                                                    //use myVar and i
                                                                    }
                                                                    public String setVar(String var){myVar=var; return this;} //Returns self instane
                                                                    }.setVar("Hello").method(3);






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Jul 28 '12 at 1:37









                                                                    Whimusical

                                                                    2,45633674




                                                                    2,45633674






























                                                                         

                                                                        draft saved


                                                                        draft discarded



















































                                                                         


                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function () {
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4732544%2fwhy-are-only-final-variables-accessible-in-anonymous-class%23new-answer', 'question_page');
                                                                        }
                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        Popular posts from this blog

                                                                        Xamarin.iOS Cant Deploy on Iphone

                                                                        Glorious Revolution

                                                                        Dulmage-Mendelsohn matrix decomposition in Python