malangi
malangi

Reputation: 2770

Java Final - an enduring mystery

suggestBox.addKeyUpHandler( new KeyUpHandler() {
  public void onKeyUp(KeyUpEvent event) {
    if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { 
      String boxText = suggestBox.getText();
      if (!boxText.equals("")) {
        suggestPanel.add(checkBoxFactory(boxText, candidateNames));
        suggestBox.setText("");
      }
    }
  }
});

I haven't been able to grasp why java forces me to declare the ArrayList (candiateNames) as final. Why is that?

Upvotes: 2

Views: 542

Answers (4)

Chris Dennett
Chris Dennett

Reputation: 22741

It's an inner class, passed into addKeyUpHandler -- all variables referenced outside an inner class need to be declared as final to be used within the inner class. This is because the local class instance must maintain a separate copy of the variable, as it may out-live the function; so as not to have the confusion of two modifiable variables with the same name in the same scope, the variable is forced to be non-modifiable.

Simply do final {type} {new-varname} = {old-varname}; before calling the method that uses the inner class, and then use {new-varname} inside that.

Upvotes: 8

Ben Lings
Ben Lings

Reputation: 29443

Because the language designers thought it would be confusing if a variable referenced by an anonymous inner class were changed. If this weren't the case all local variable references referenced by the anonymous class would have to be lifted to be fields of that class.

Upvotes: 0

user177800
user177800

Reputation:

so that it can't change out from under the anonymous inner class KeyUpHandler implementation.

Upvotes: 0

missingfaktor
missingfaktor

Reputation: 92086

Because Java doesn't have *real closures* ! ;-)

See this post to know how this is actually implemented.

Upvotes: 2

Related Questions