Why are only final variables accessible in anonymous class?

  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 
            }
        });
    }
    

15 Answers
15

Leave a Comment